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.