9.1 Understanding Exceptions
- Exceptions are events that occur during the execution of a program and disrupt the normal flow of the program.
- They can occur due to various reasons, such as invalid input, resource unavailability, or unexpected errors.
- Exception handling is a mechanism to gracefully handle these exceptions and prevent the program from crashing.
9.2 Handling Exceptions with try-catch:
- The “try-catch” block is used to catch and handle exceptions. The code that may throw an exception is placed inside the “try” block, and the potential exceptions are caught and handled in the
- catch block.
- Here's an example:
public class ExceptionHandlingExample {
public static void main(String[] args) {
try {
int result = divide(10, 0);
System.out.println("Result: " + result);
} catch (ArithmeticException e) {
System.out.println("Error: " + e.getMessage());
}
}
public static int divide(int num1, int num2) {
return num1 / num2;
}
}
Output:
Error: / by zero
- In this example, the divide method throws an ArithmeticException when dividing by zero.
- The exception is caught in the catch block, and an error message is printed.
- This prevents the program from terminating abruptly.
9.3 Throwing Exceptions:
- In addition to handling exceptions, you can also explicitly throw exceptions using the “throw” keyword.
- This is useful when you want to indicate an exceptional condition in your program.
- Here's an example:
public class ExceptionThrowingExample {
public static void main(String[] args) {
try {
int result = calculateSquareRoot(-9);
System.out.println("Result: " + result);
} catch (IllegalArgumentException e) {
System.out.println("Error: " + e.getMessage());
}
}
public static int calculateSquareRoot(int number) {
if (number < 0) {
throw new IllegalArgumentException("Number cannot be negative.");
}
return (int) Math.sqrt(number);
}
}
Error: Number cannot be negative.
- In this example, the calculateSquareRoot method throws an IllegalArgumentException if the number passed is negative.
- The exception is caught in the catch block, and an error message is displayed.
9.4 Finally Block:
The “finally” block is used to specify code that should be executed regardless of whether an exception occurs or not. It is often used to release resources or perform cleanup operations.
Here's an example:
public class FinallyBlockExample {
public static void main(String[] args) {
try {
int result = divide(10, 0);
System.out.println("Result: " + result);
} catch (ArithmeticException e) {
System.out.println("Error: " + e.getMessage());
} finally {
System.out.println("Finally block executed.");
}
}
public static int divide(int num1, int num2) {
try {
return num1 / num2;
} catch (ArithmeticException e) {
throw e;
} finally {
System.out.println("Division operation completed.");
}
}
}
- In this example, the finally block is used to print a message indicating the completion of the division operation, regardless of whether an exception occurred or not.
- By understanding and implementing exception handling, you can make your programs more robust and handle unexpected situations gracefully.
- Exception handling allows you to identify and recover from errors, ensuring that your program continues to run smoothly.