Exception Handling - JAVA

Cards (18)

  • Exception
    An event that disrupts the normal flow of the program. It is an object which is thrown at runtime.
  • Exception Handling
    A mechanism to handle runtime errors such as ClassNotFoundException, IOException, SQLException, RemoteException, etc.
  • Significance of Exception Handling in Java
    • Error Handling: Exceptions provide a mechanism to handle errors and exceptional conditions gracefully. Instead of abruptly terminating the program, exceptions allow the program to respond to errors in a controlled manner.
    • Separation of Error-Handling Code: By using exceptions, error-handling code can be separated from the main logic of the program, improving code readability and maintainability. This separation allows developers to focus on writing clean, functional code while handling errors separately.
    • Program Robustness: Exception handling contributes to the robustness of Java programs by preventing unexpected crashes or terminations. By anticipating and handling potential errors, developers can write more reliable and resilient applications.
    • Debugging and Diagnostics: Exceptions provide valuable information about the cause of errors, including the type of exception, stack trace, and error message. This information aids in debugging and diagnosing issues during the development and testing phases.
    • Resource Management: Exceptions play a crucial role in resource management, especially in handling I/O operations, database connections, and other resources. Properly handling exceptions ensures that resources are released and cleaned up appropriately, preventing resource leaks and improving resource utilization.
    • Control Flow Alteration: Exceptions allow for altering the control flow of the program based on exceptional conditions. By catching and handling exceptions, developers can redirect program execution, recover from errors, or take appropriate corrective actions.
  • Types of Java Exceptions
    • Checked Exceptions: Exceptions that the compiler requires the programmer to either handle using a try-catch block or declare in the method signature using the throws keyword. Examples: IOException, FileNotFoundException, SQLException.
    • Unchecked Exceptions: Exceptions that do not require handling or declaration by the programmer. They typically represent programming errors or conditions that are beyond the programmer's control. Examples: NullPointerException, ArrayIndexOutOfBoundsException, ArithmeticException.
  • Java Exception Keywords
    try - This keyword is used to specify a block.
    catch - This keyword is used to handle the exception.
    finally - This keyword is used to execute the necessary code.
    throw - This keyword is used to throw an exception.
    throws - This keyword is used to declare exceptions.
  • Java Exception Handling Example
    • public class JavaExceptionExample {
    public static void main(String args[]){
    try{
    //code that may raise exception
    int data=100/0;
    }catch(ArithmeticException e){System.out.println(e);}
    //rest code of the program
    System.out.println("rest of the code...");
    }
    }
  • Common Scenarios of Java Exceptions
    • ArithmeticException: Occurs when dividing any number by zero.
    • NullPointerException: Occurs when performing an operation on a null value.
    • NumberFormatException: Occurs when the formatting of a variable or number is mismatched.
    • ArrayIndexOutOfBoundsException: Occurs when an array exceeds its size.
  • Java try-catch block
    The try block is used to enclose the code that might throw an exception. The try block must be followed by either a catch or finally block.
  • Java catch block
    The catch block is used to handle the Exception by declaring the type of exception within the parameter. The declared exception must be the parent class exception (i.e., Exception) or the generated exception type.
  • Problem without exception handling
    • public class TryCatchExample1 {
    public static void main(String[] args) {
    int data=50/0; //may throw exception
    System.out.println("rest of the code");
    }
    }
  • Solution by exception handling
    • public class TryCatchExample2 {
    public static void main(String[] args) {
    try {
    int data=50/0; //may throw exception
    }
    catch(ArithmeticException e) {
    System.out.println(e);
    }
    System.out.println("rest of the code");
    }
    }
  • Using the Exception class

    • public class TryCatchExample4 {
    public static void main(String[] args) {
    try {
    int data=50/0; //may throw exception
    }
    catch(Exception e) {
    System.out.println(e);
    }
    System.out.println("rest of the code");
    }
    }
  • Using the Custom Message
    • public class TryCatchExample5 {
    public static void main(String[] args) {
    try {
    int data=50/0; //may throw exception
    }
    catch(Exception e) {
    System.out.println("Can not be divided by zero");
    }
    }
    }
  • Resolving the exception in a catch block
    • public class TryCatchExample6 {
    public static void main(String[] args) {
    int i=50;
    int j=0;
    int data;
    try {
    data=i/j; //may throw exception
    }
    catch(Exception e) {
    System.out.println(i/(j+2)); // resolving the exception in catch block
    }
    }
    }
  • Resolving the exception in a catch block
    • public class TryCatchExample6 {
    public static void main(String[] args) {
    try {
    int arr[]= {1,3,5,7};
    System.out.println(arr[10]); //may throw exception
    }
    catch(ArrayIndexOutOfBoundsException e) {
    System.out.println(e);
    }
    System.out.println("rest of the code");
    }
    }
  • Java Catch Multiple Exceptions
    A try block can be followed by one or more catch blocks. Each catch block must contain a different exception handler.
  • Points to remember
    •At a time only one exception occurs and at a time only one catch block is executed.
    •All catch blocks must be ordered from most specific to most general, i.e. catch for ArithmeticException must come before catch for Exception.
  • MultipleCatchBlock1.java
    • public class MultipleCatchBlock1 {
    public static void main(String[] args) {
    try {
    int a[] = new int[5];
    a[5] = 30/0;
    }
    catch(ArithmeticException e) {
    System.out.println("Arithmetic Exception occurs");
    }
    catch(ArrayIndexOutOfBoundsException e) {
    System.out.println("ArrayIndexOutOfBounds Exception occurs");
    }
    catch(Exception e) {
    System.out.println("Parent Exception occurs");
    }
    System.out.println("rest of the code");
    }
    }