WikiGalaxy

Personalize

Java Exceptions

Introduction to Exceptions:

Exceptions in Java are events that disrupt the normal flow of a program's instructions. They occur during the execution of a program and can be of various types, such as checked and unchecked exceptions.

Types of Exceptions:

Java exceptions are broadly categorized into checked exceptions, unchecked exceptions, and errors. Checked exceptions are checked at compile-time, while unchecked exceptions occur during runtime.


import java.io.*;
class Example {
  public static void main(String args[]) {
      try {
          FileInputStream file = new FileInputStream("test.txt");
      } catch (FileNotFoundException e) {
          System.out.println("File not found exception occurred.");
      }
  }
}
    

Handling Exceptions:

Java provides a powerful mechanism to handle exceptions using try, catch, and finally blocks. This ensures the program continues running even when an exception occurs.

Console Output:

File not found exception occurred.

Java Exceptions

Try-Catch Block:

The try block contains the code that might throw an exception, while the catch block handles the exception. Multiple catch blocks can be used to handle different types of exceptions.


class Example {
  public static void main(String args[]) {
      try {
          int data = 100 / 0;
      } catch (ArithmeticException e) {
          System.out.println("Arithmetic Exception: Division by zero.");
      }
  }
}
    

Multiple Catch Blocks:

Java allows the use of multiple catch blocks to handle different exceptions separately. This is useful for debugging and maintaining code clarity.

Console Output:

Arithmetic Exception: Division by zero.

Java Exceptions

Finally Block:

The finally block in Java is used to execute important code such as closing resources, regardless of whether an exception is thrown or not.


class Example {
  public static void main(String args[]) {
      try {
          int data = 100 / 0;
      } catch (ArithmeticException e) {
          System.out.println("Exception caught.");
      } finally {
          System.out.println("Finally block is always executed.");
      }
  }
}
    

Importance of Finally:

The finally block is crucial for resource cleanup and ensuring that certain actions are performed after a try-catch block, regardless of the outcome.

Console Output:

Exception caught. Finally block is always executed.

Java Exceptions

Throw Keyword:

The throw keyword in Java is used to explicitly throw an exception from a method or any block of code.


class Example {
  static void checkAge(int age) {
      if (age < 18)
          throw new ArithmeticException("Not eligible for voting.");
      else
          System.out.println("Eligible for voting.");
  }
  public static void main(String args[]) {
      checkAge(16);
  }
}
    

Using Throw:

The throw keyword is used to create a custom exception message and throw it to the caller. It is useful for validating conditions and handling specific cases.

Console Output:

Exception in thread "main" java.lang.ArithmeticException: Not eligible for voting.

Java Exceptions

Throws Keyword:

The throws keyword in Java is used in method signature to declare an exception. It notifies the caller of the method about the exceptions that might occur.


import java.io.*;
class Example {
  void method() throws IOException {
      throw new IOException("Device error");
  }
  public static void main(String args[]) {
      try {
          Example obj = new Example();
          obj.method();
      } catch (IOException e) {
          System.out.println("Exception handled: " + e);
      }
  }
}
    

Using Throws:

The throws keyword is used to specify that a method can throw one or more exceptions, thus allowing exception handling to be deferred to the caller of the method.

Console Output:

Exception handled: java.io.IOException: Device error

Java Exceptions

Custom Exceptions:

Java allows the creation of custom exceptions by extending the Exception class. This is useful for defining application-specific error conditions.


class CustomException extends Exception {
  CustomException(String message) {
      super(message);
  }
}
class Example {
  public static void main(String args[]) {
      try {
          throw new CustomException("Custom exception occurred");
      } catch (CustomException e) {
          System.out.println(e.getMessage());
      }
  }
}
    

Creating Custom Exceptions:

Custom exceptions provide a way to encapsulate error information and handle specific error scenarios unique to an application.

Console Output:

Custom exception occurred

Java Exceptions

Exception Propagation:

Exception propagation refers to the process by which an exception is passed up the call stack until it is handled. Java supports this mechanism to simplify error handling.


class Example {
  void method1() {
      int data = 50 / 0;
  }
  void method2() {
      method1();
  }
  void method3() {
      try {
          method2();
      } catch (ArithmeticException e) {
          System.out.println("Exception handled: " + e);
      }
  }
  public static void main(String args[]) {
      Example obj = new Example();
      obj.method3();
  }
}
    

Understanding Propagation:

Exception propagation allows an exception to be caught in a method higher up the call stack, enabling centralized error handling.

Console Output:

Exception handled: java.lang.ArithmeticException: / by zero

Java Exceptions

Checked vs. Unchecked Exceptions:

Checked exceptions are checked at compile-time, while unchecked exceptions occur at runtime. Understanding the difference helps in effective exception handling.


import java.io.*;
class Example {
  void checkedExceptionMethod() throws IOException {
      throw new IOException("Checked exception");
  }
  void uncheckedExceptionMethod() {
      int data = 50 / 0; // Unchecked exception
  }
  public static void main(String args[]) {
      Example obj = new Example();
      try {
          obj.checkedExceptionMethod();
      } catch (IOException e) {
          System.out.println("Checked Exception caught: " + e);
      }
      try {
          obj.uncheckedExceptionMethod();
      } catch (ArithmeticException e) {
          System.out.println("Unchecked Exception caught: " + e);
      }
  }
}
    

Handling Different Exceptions:

Checked exceptions must be declared in a method or constructor's throws clause if they can be thrown by the execution of the method or constructor and propagate outside the method or constructor boundary.

Console Output:

Checked Exception caught: java.io.IOException: Checked exception Unchecked Exception caught: java.lang.ArithmeticException: / by zero

Java Exceptions

Try with Resources:

The try-with-resources statement is a try statement that declares one or more resources. A resource is an object that must be closed after the program is finished with it.


import java.io.*;
class Example {
  public static void main(String args[]) {
      try (FileReader fr = new FileReader("test.txt")) {
          int i;
          while ((i = fr.read()) != -1) {
              System.out.print((char) i);
          }
      } catch (IOException e) {
          System.out.println("IOException handled: " + e);
      }
  }
}
    

Benefits of Try with Resources:

Try-with-resources ensures that each resource is closed at the end of the statement. This feature eliminates the need for explicit resource management and reduces boilerplate code.

Console Output:

IOException handled: java.io.FileNotFoundException: test.txt (No such file or directory)

logo of wikigalaxy

Newsletter

Subscribe to our newsletter for weekly updates and promotions.

Privacy Policy

 • 

Terms of Service

Copyright © WikiGalaxy 2025