what is exception handling in java with example
Exception handling in Java is a mechanism used to handle runtime errors (exceptions) gracefully, allowing the program to recover from unexpected situations without crashing. Java provides a robust exception handling mechanism through the use of try
, catch
, finally
, throw
, and throws
keywords.
Basic Exception Handling Structure:
Basic Exception Handling example
try {
// Code that might cause an exception
} catch (ExceptionType e) {
// Code to handle the exception
} finally {
// Code that will be executed regardless of whether an exception occurred or not
}
Here’s an explanation of the keywords and their roles:
try
Block: The code that might throw an exception is placed inside thetry
block.catch
Block: If an exception occurs within thetry
block, it is caught and handled in the correspondingcatch
block. The catch block specifies the type of exception it can handle. You can have multiple catch blocks to handle different types of exceptions.finally
Block: Thefinally
block contains code that will be executed regardless of whether an exception occurred or not. It is often used for cleanup tasks, such as closing files or releasing resources.throw
Keyword: Thethrow
keyword is used to explicitly throw an exception. You can throw either a built-in exception or a custom exception.throws
Keyword: Thethrows
keyword is used in method declarations to indicate that the method might throw certain exceptions. It notifies the caller that they need to handle those exceptions.
Example of Exception Handling:
Exception example
import java.util.InputMismatchException;
import java.util.Scanner;
/*
* Author: Zameer Ali Mohil
* */
public class ExceptionHandlingExample {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
try {
System.out.print("Enter a number: ");
int num = scanner.nextInt(); // This might cause an InputMismatchException
int result = 10 / num; // This might cause an ArithmeticException
System.out.println("Result: " + result);
} catch (InputMismatchException e) {
System.out.println("Invalid input. Please enter a number.");
} catch (ArithmeticException e) {
System.out.println("Cannot divide by zero.");
} finally {
System.out.println("This block always executes, regardless of exceptions.");
scanner.close();
}
}
}
In this example:
- The
try
block contains code that might throwInputMismatchException
orArithmeticException
. - The
catch
blocks handle these exceptions and provide appropriate error messages. - The
finally
block closes theScanner
object, ensuring that it is always closed, even if an exception occurs.
Exception handling helps prevent program crashes due to unexpected situations, making Java programs more robust and reliable.