Exception Handling in Java
Exception handling is a mechanism in Java used to handle runtime errors and maintain the normal flow of a program.
An exception is an unwanted event that occurs during program execution, such as dividing a number by zero or accessing an invalid array index.
Why Exception Handling?
Exception handling helps to:
- Prevent abnormal program termination.
- Handle runtime errors.
- Maintain the normal flow of the program.
- Display meaningful error messages.
- Separate error-handling code from normal code.
Types of Exceptions
1. Checked Exception
Checked exceptions are checked by the compiler at compile time.
Examples:
IOExceptionSQLExceptionFileNotFoundException
2. Unchecked Exception
Unchecked exceptions occur at runtime.
Examples:
ArithmeticExceptionNullPointerExceptionArrayIndexOutOfBoundsException
Exception Handling Keywords
Java provides five important keywords:
trycatchfinallythrowthrows
1. try
The try block contains code that may cause an exception.
try { int result = 10 / 0; }
2. catch
The catch block handles an exception generated inside the try block.
try { int result = 10 / 0; } catch (ArithmeticException e) { System.out.println("Cannot divide by zero"); }
Output
Cannot divide by zero
3. finally
The finally block normally executes whether an exception occurs or not. It is commonly used for cleanup operations.
try { System.out.println("Try block"); } catch (Exception e) { System.out.println("Exception occurred"); } finally { System.out.println("Finally block"); }
Output
Try block Finally block
4. throw
The throw keyword is used to explicitly create and throw an exception.
class Main { public static void main(String[] args) { int age = 15; if (age < 18) { throw new ArithmeticException("Not eligible"); } } }
5. throws
The throws keyword is used in a method declaration to indicate that the method may pass specified exceptions to its caller.
import java.io.IOException; class Main { static void readFile() throws IOException { // File operation } }
Multiple Catch Blocks
Multiple catch blocks can handle different types of exceptions.
try { int[] numbers = {10, 20, 30}; System.out.println(numbers[5]); } catch (ArithmeticException e) { System.out.println("Arithmetic error"); } catch (ArrayIndexOutOfBoundsException e) { System.out.println("Invalid array index"); }
Output
Invalid array index
Try-Catch-Finally Structure
try | |-- Exception occurs | catch | finally
Example:
try { // Risky code } catch (Exception e) { // Handle exception } finally { // Cleanup code }
Exception Hierarchy
The basic hierarchy is:
Throwable ├── Error └── Exception ├── RuntimeException └── Other Exceptions
Error generally represents serious problems, while Exception represents conditions that applications may handle.
Advantages of Exception Handling
- Prevents unexpected program termination.
- Makes programs more reliable.
- Provides meaningful error messages.
- Separates error handling from normal program logic.
- Helps maintain the normal flow of execution.
- Makes debugging and maintenance easier.
Key Points
trycontains potentially risky code.catchhandles exceptions.finallyis used for cleanup code.throwexplicitly throws an exception.throwsdeclares exceptions that a method may pass to its caller.- Exceptions can be built-in or user-defined.
Conclusion
Exception handling is an important feature of Java that allows programmers to detect, handle, and manage runtime problems without unnecessarily terminating the program. The try, catch, finally, throw, and throws keywords provide the main mechanisms for handling exceptions.