Exception handling in Java is a powerful feature that enables a program to manage and recover gracefully from unexpected situations or errors that might occur during program execution. Exception handling provides a mechanism to intercept and manage exceptions, preventing the abrupt termination of the program and ensuring robust error handling.
The process of exception handling in Java revolves around five key components: try block, catch block, finally block, throw keyword, and throws keyword.
1. Try Block:
A try block is used to enclose code that might potentially throw an exception. It marks the section of code where an exception may occur. If an exception is thrown within the try block, the control is transferred to the matching catch block.
Syntax:
try
{
// Code that might throw an exception.
}
catch (ExceptionType1 ex)
{
// Handle ExceptionType1.
}
catch (ExceptionType2 ex)
{
// Handle ExceptionType2.
}
In this structure, the try block contains a sequence of statements that could throw exceptions. If an exception is thrown, the program's control is transferred to the catch block that can handle that particular exception. If no appropriate catch block is found, the program terminates abruptly.
2. Catch Block:
A catch block is used to handle a specific type of exception that can be thrown within the try block. It specifies the exception type it can catch and provides the necessary code to handle the exception.
Syntax:
catch (ExceptionType ex)
{
// Exception handling code.
}
The catch block is placed immediately after the try block and consists of the catch keyword followed by the exception type in parentheses. When an exception is thrown within the try block, the program control jumps to the catch block that matches the thrown exception's type.
3. Finally Block:
The finally block is a segment of code that is always executed after a try/catch block, regardless of whether an exception was thrown or not. This is typically used for cleaning up resources such as closing files or database connections.
Syntax:
finally
{
// Code that always gets executed.
}
4. Throw Keyword:
The throw keyword in Java is used to explicitly throw an exception from a method or any block of code. We can throw either checked or unchecked exception. The throw keyword is mainly used to throw custom exceptions.
Syntax:
throw exceptionObject; // Throws an exception of a specific type.
Here's an example that demonstrates the use of exception handling in Java:
import java.util.Scanner;
class Main
{
public static void main(String[] args)
{
Scanner scanner = new Scanner(System.in);
try {
System.out.print("Enter an integer: ");
int number = scanner.nextInt();
if (number < 0)
{
throw new IllegalArgumentException("Negative number entered");
}
System.out.println("You entered " + number);
}
catch (Exception ex)
{
System.out.println("Exception caught: " + ex.getMessage());
}
finally
{
scanner.close();
System.out.println("Scanner closed.");
}
}
}
In this example, the user is asked to enter an integer. If the entered number is negative, an 'IllegalArgumentException' is explicitly 'thrown' using the throw keyword.