Skip to main content

14. Exception Handling in Java

πŸ“ Exception handling in Java is a powerful mechanism that allows developers to handle runtime errors gracefully, improving program stability and user experience.

1. What is an Exception?​

  • An exception is an event that disrupts the normal flow of a program's execution.
  • Exceptions can be caused by various factors, such as invalid input, resource unavailability, or hardware failure.

2. Types of Exceptions​

Exceptions in Java can be broadly categorized into two main types:

2.1. Checked Exceptions​

  • These are exceptions that are checked at compile-time.
  • The programmer must handle them using try-catch blocks or declare them using the throws keyword.

Example:​

import java.io.FileReader;
import java.io.IOException;

public class CheckedExample {
public static void main(String[] args) {
try {
FileReader fr = new FileReader("file.txt");
} catch (IOException e) {
System.out.println("File not found: " + e.getMessage());
}
}
}

2.2. Unchecked Exceptions​

  • These exceptions are not checked at compile-time, meaning the programmer does not have to handle them explicitly.
  • They extend the RuntimeException class.

Example:​

public class UncheckedExample {
public static void main(String[] args) {
int[] numbers = {1, 2, 3};
System.out.println(numbers[3]); // This will throw ArrayIndexOutOfBoundsException
}
}

3. The Exception Hierarchy​

  • All exceptions in Java are derived from the Throwable class.
  • The hierarchy includes two main subclasses:
    • Error: Represents serious problems that a reasonable application should not try to catch.
    • Exception: Represents conditions that a user program should catch.

4. Exception Handling Keywords​

4.1. try​

  • The try block is used to wrap code that might throw an exception.

4.2. catch​

  • The catch block is used to handle the exception.

Example:​

try {
// Code that may throw an exception
} catch (ExceptionType e) {
// Code to handle the exception
}

4.3. finally​

  • The finally block is used to execute code regardless of whether an exception is thrown or not. It is typically used for cleanup activities.

Example:​

try {
// Code that may throw an exception
} catch (ExceptionType e) {
// Handle exception
} finally {
// Cleanup code (always executes)
}

4.4. throw​

  • The throw keyword is used to explicitly throw an exception.

Example:​

public void validateAge(int age) {
if (age < 18) {
throw new IllegalArgumentException("Age must be at least 18");
}
}

4.5. throws​

  • The throws keyword is used in method declarations to specify that a method can throw exceptions.

Example:​

public void readFile() throws IOException {
// Code that may throw an IOException
}

5. Custom Exceptions​

You can create your own exceptions by extending the Exception class.

Example:​

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

public class CustomExceptionExample {
public static void main(String[] args) {
try {
throw new CustomException("This is a custom exception!");
} catch (CustomException e) {
System.out.println(e.getMessage());
}
}
}

6. Summary of Exception Handling​

FeatureDescription
DefinitionMechanism to handle runtime errors.
TypesChecked and Unchecked exceptions.
HierarchyDerived from Throwable.
Keywordstry, catch, finally, throw, throws.
Custom ExceptionsExtend the Exception class to create your own exceptions.

Exception handling is essential for building robust Java applications that can gracefully handle errors and maintain a good user experience.