Exception handling in Java is a mechanism that allows you to gracefully handle unexpected or erroneous situations that may occur during program execution. Java provides a robust exception handling framework using the try, catch, finally, and throw keywords. Here are some examples of exception handling in Java:
1. Basic Try-Catch:
publicclassBasicExceptionHandling {publicstaticvoidmain(String[] args) {try {int result =10/0; // This will throw an ArithmeticException } catch (ArithmeticException e) {System.err.println("An ArithmeticException occurred: "+e.getMessage()); } }}
In this example, we attempt to divide by zero, which results in an ArithmeticException. We catch this exception and print an error message.
2. Multiple Catch Blocks:
publicclassMultipleCatchBlocks {publicstaticvoidmain(String[] args) {try {int[] numbers = {1,2,3};int result = numbers[4]; // This will throw an ArrayIndexOutOfBoundsException } catch (ArrayIndexOutOfBoundsException e) {System.err.println("An ArrayIndexOutOfBoundsException occurred: "+e.getMessage()); } catch (Exception e) {System.err.println("A general exception occurred: "+e.getMessage()); } }}
Here, we catch both a specific exception (ArrayIndexOutOfBoundsException) and a more general exception (Exception) to handle different types of exceptions gracefully.
3. Finally Block:
publicclassFinallyBlockExample {publicstaticvoidmain(String[] args) {try {int result =10/0; // This will throw an ArithmeticException } catch (ArithmeticException e) {System.err.println("An ArithmeticException occurred: "+e.getMessage()); } finally {System.out.println("This block always executes, whether an exception occurs or not."); } }}
The finally block is executed no matter what, even if an exception occurs or not. It's typically used for cleanup operations like closing resources.
You can create your own custom exceptions by extending the Exception class. In this example, we create a custom exception called MyCustomException.
5. Rethrowing an Exception:
publicclassRethrowExceptionExample {publicstaticvoidmain(String[] args) throwsException {try {doSomething(); } catch (Exception e) {System.err.println("Caught exception: "+e.getMessage());throw e; // Rethrow the exception } }staticvoiddoSomething() throwsException {// Some code that may throw an exceptionthrownewException("An exception occurred in doSomething."); }}
You can catch an exception, perform some actions, and then rethrow the same exception or a different one.
Remember that good exception handling practices involve providing meaningful error messages, handling exceptions at the appropriate level of your program, and releasing resources in the finally block.