Java Tutorial

Operators

Flow Control

String

Number and Date

Built-in Classes

Array

Class and Object

Inheritance and Polymorphism

Exception Handling

Collections, Generics and Enumerations

Reflection

Input/Output Stream

Annotation

Java Exception Handling And Common Exceptions

Exception handling is a crucial concept in Java programming. It helps you gracefully deal with errors and maintain the normal flow of your program. In this tutorial, we will discuss Java exception handling and explore some common exceptions you may encounter.

  • Java Exceptions An exception is an event that occurs during the execution of a program, disrupting its normal flow. Java exceptions are objects that are instances of a subclass of the Throwable class. There are two main types of exceptions:

a. Checked Exceptions: These are exceptions that must be explicitly caught or declared in a method's throws clause. They usually represent recoverable conditions, such as FileNotFoundException.

b. Unchecked Exceptions: These exceptions are not required to be explicitly caught or declared. They typically represent programming errors, such as NullPointerException.

  • Exception Handling Mechanism Java provides a mechanism to handle exceptions using the try-catch-finally construct.

a. try block: Encloses the code that might throw an exception.

b. catch block: Catches and handles the exception thrown by the try block. You can have multiple catch blocks to handle different exceptions.

c. finally block: Executes regardless of whether an exception is thrown or caught. It is typically used to release resources.

Example:

try {
    // Code that might throw an exception
} catch (ExceptionType1 e) {
    // Handle ExceptionType1
} catch (ExceptionType2 e) {
    // Handle ExceptionType2
} finally {
    // Cleanup code
}
  • Common Exceptions in Java Here are some common exceptions you may encounter:

a. NullPointerException: Occurs when you try to access a method or field of a null object reference.

b. ArrayIndexOutOfBoundsException: Occurs when you try to access an array element with an index that is out of bounds.

c. FileNotFoundException: Occurs when a file cannot be found or accessed.

d. IOException: Represents an error that occurs during input or output operations, such as reading or writing a file.

e. NumberFormatException: Occurs when trying to parse a string to a numeric type, but the string is not formatted correctly.

f. ArithmeticException: Occurs when an arithmetic operation, such as division by zero, results in an error.

Example:

public class ExceptionHandlingExample {
    public static void main(String[] args) {
        try {
            int[] numbers = {1, 2, 3};
            System.out.println(numbers[3]);
        } catch (ArrayIndexOutOfBoundsException e) {
            System.out.println("Array index is out of bounds.");
        } catch (NullPointerException e) {
            System.out.println("Null pointer exception occurred.");
        } finally {
            System.out.println("This will always execute.");
        }
    }
}

In this example, an ArrayIndexOutOfBoundsException occurs, so the corresponding catch block is executed. The finally block is executed regardless of the exception.

  • Custom Exceptions You can create custom exceptions by extending the Exception class or one of its subclasses. This allows you to create specific exceptions for your application's needs.

Example:

class CustomException extends Exception {
    public CustomException(String message) {
        super(message);
    }
}

To use the custom exception, you can throw it using the throw keyword:

public void checkAge(int age) throws CustomException {
    if (age < 18) {
        throw new CustomException("Age must be 18 or older.");
    }
}

Remember that understanding and handling exceptions properly can make your code more robust and easier to maintain. Practice and familiarize yourself with common exceptions and how to handle them effectively.

  1. try, catch, and finally blocks in Java

    The try block contains the code that might throw an exception. The catch block handles the exception, and the finally block ensures code execution, whether an exception occurs or not.

    try {
        // Code that may throw an exception
    } catch (ExceptionType ex) {
        // Handle the exception
    } finally {
        // Code to execute regardless of whether an exception occurred
    }
    
  2. Common exceptions in Java and their meanings

    Common exceptions include NullPointerException, ArrayIndexOutOfBoundsException, ArithmeticException, and FileNotFoundException. Each indicates a specific error in the code.

    try {
        // Code that may throw exceptions
    } catch (NullPointerException e) {
        // Handle null references
    } catch (ArrayIndexOutOfBoundsException e) {
        // Handle array index out of bounds
    } catch (ArithmeticException e) {
        // Handle arithmetic errors
    } catch (Exception e) {
        // Handle other exceptions
    }
    
  3. Custom exception handling in Java

    You can create custom exceptions by extending the Exception class. This allows you to define your own exception types.

    class CustomException extends Exception {
        // Custom exception code
    }
    
    try {
        throw new CustomException();
    } catch (CustomException e) {
        // Handle custom exception
    }
    
  4. Checked vs. unchecked exceptions in Java

    Checked exceptions are checked at compile time and must be either caught or declared. Unchecked exceptions (RuntimeExceptions) don't require explicit handling.

    // Checked exception (must be caught or declared)
    try {
        throw new IOException();
    } catch (IOException e) {
        // Handle or declare
    }
    
    // Unchecked exception
    throw new RuntimeException();
    
  5. Throwing exceptions in Java with throw keyword

    The throw keyword is used to explicitly throw an exception.

    if (condition) {
        throw new CustomException();
    }
    
  6. Exception propagation in Java

    Exceptions can propagate up the call stack if not caught. Each method in the call stack is given a chance to handle the exception.

    public void methodA() {
        methodB();
    }
    
    public void methodB() {
        // Exception occurs here and propagates to methodA if not caught
    }
    
  7. Handling multiple exceptions in Java

    You can handle multiple exceptions in a single catch block or use multiple catch blocks for different exceptions.

    try {
        // Code that may throw exceptions
    } catch (IOException | SQLException e) {
        // Handle IOException or SQLException
    }
    
  8. Java StackTrace and debugging exceptions

    The stack trace provides information about the call stack when an exception occurs. It helps in debugging.

    try {
        // Code that may throw an exception
    } catch (Exception e) {
        e.printStackTrace();
    }