1. Introduction
throw
, throws
, and finally
keywords. 2. Step-by-Step Guide
Exception Handling: Exception handling in Java is a powerful mechanism that is used to handle the runtime errors, compile-time errors are not handled by exception handling in Java.
Examples:
try-catch block: The try block contains a set of statements where an exception can occur. The catch block contains the exception handler which processes the exception.
java
try {
// Code that may throw an exception
} catch (ExceptionType name) {
// Code to handle the Exception
}
- finally block: The finally block always executes when the try block exits, providing a perfect place for cleanup code.
java
try {
// Code that may throw an exception
} catch (ExceptionType name) {
// Code to handle the Exception
} finally {
// Cleanup code
}
3. Code Examples
ArrayIndexOutOfBoundsException
java
public class Main {
public static void main(String[] args) {
try {
int[] array = new int[5];
System.out.println(array[10]); // This line will throw an exception
} catch (ArrayIndexOutOfBoundsException e) {
System.out.println("Exception caught: " + e);
}
}
}
This will output: Exception caught: java.lang.ArrayIndexOutOfBoundsException: Index 10 out of bounds for length 5
java
public class Main {
public static void main(String[] args) {
try {
int[] array = new int[5];
System.out.println(array[10]); // This line will throw an exception
} catch (ArrayIndexOutOfBoundsException e) {
System.out.println("Exception caught: " + e);
} finally {
System.out.println("This line always executed.");
}
}
}
This will output:
Exception caught: java.lang.ArrayIndexOutOfBoundsException: Index 10 out of bounds for length 5
This line always executed.
4. Summary
Key Points:
- Exception handling is crucial in building robust applications that can handle unexpected events gracefully.
- The try-catch block is used to handle exceptions.
- The finally block is used for cleanup tasks and always executes, regardless of whether an exception was thrown.
Next Steps:
- Learn about different types of exceptions in Java.
- Understand how to create custom exceptions.
Additional Resources:
- Java Documentation on Exceptions
- Oracle tutorial on Handling Exceptions
5. Practice Exercises
Exercise 1: Write a program where you intentionally divide by zero. Handle this exception and print a user-friendly message.
Exercise 2: Create a scenario where a NullPointerException
could occur. Handle this exception and print a user-friendly message.
Exercise 3: Create a scenario where an array index is out of bounds. Handle this exception and make sure to include a finally block that prints a statement.
Note: Remember to practice, revise, and understand these concepts thoroughly, as they are fundamental in Java programming.