Exception handling in Java is a mechanism to handle runtime errors, known as exceptions, in a structured manner. Exceptions occur when an unexpected condition or error arises during program execution. By using exception handling, you can catch and handle these exceptions, allowing your program to gracefully handle errors and prevent abrupt termination.
Java provides a built-in exception handling framework that consists of the following elements:
Exception: An exception is an event that occurs during program execution and disrupts the normal flow of the program. It can be caused by various factors, such as invalid input, resource unavailability, or programming errors.
try-catch: The try-catch block is used to catch and handle exceptions. The try block contains the code that might throw an exception, and the catch block handles the exception if it occurs. Multiple catch blocks can be used to handle different types of exceptions.
finally: The finally block is optional and is used to define code that should be executed regardless of whether an exception occurred or not. It is typically used to release resources or perform cleanup operations.
throw: The throw keyword is used to explicitly throw an exception. It is used when you want to manually raise an exception based on a specific condition.
Here are some commonly used exception types in Java:
ArithmeticException:
Thrown when an arithmetic operation fails, such as division by zero.
NullPointerException:
Thrown when you try to access or manipulate an object that is null.
ArrayIndexOutOfBoundsException:
Thrown when you try to access an array element with an invalid index.
FileNotFoundException:
Thrown when a file is not found at the specified path.
IOException:
A general exception class for Input/Output operations.
NumberFormatException:
Thrown when you try to convert a string to a numeric type, but the string is not a valid number.
Here's the syntax for exception handling in Java:
try { // Code that might throw an exception } catch (ExceptionType1 e1) { // Handle exception of type ExceptionType1 } catch (ExceptionType2 e2) { // Handle exception of type ExceptionType2 } finally { // Code to be executed regardless of whether an exception occurred or not }
And here's an example that demonstrates exception handling in Java:
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("An error occurred: " + e.getMessage()); } finally { System.out.println("Finally block executed"); } } public static int divide(int num1, int num2) { return num1 / num2; } }
In this example, we have a divide() method that performs division between two numbers. Inside the main method, we call the divide() method with parameters 10 and 0, which will result in an ArithmeticException due to division by zero. The exception is caught in the catch block, and an error message is displayed. Finally, the finally block is executed regardless of whether an exception occurred or not.