Introduction
The Exception
class in Java is the root class for handling exceptions. It represents errors that can occur during the execution of a program, allowing you to manage these situations gracefully.
Table of Contents
- What is
Exception
? - Types of Exceptions
- Handling Exceptions
- Examples of Exception Handling
- Conclusion
1. What is Exception?
Exception
is the superclass for all exceptions in Java, indicating conditions that a reasonable application might want to catch. It is part of Java’s exception handling mechanism.
2. Types of Exceptions
- Checked Exceptions: Must be caught or declared in the method signature (e.g.,
IOException
,SQLException
). - Unchecked Exceptions: Also known as runtime exceptions, they do not need to be declared or caught (e.g.,
NullPointerException
,ArithmeticException
).
3. Handling Exceptions
To handle exceptions, use a try-catch block. The try
block contains code that might throw an exception, while the catch
block handles the exception.
4. Examples of Exception Handling
Example 1: Handling a Checked Exception
This example demonstrates handling a FileNotFoundException
.
import java.io.File; import java.io.FileNotFoundException; import java.util.Scanner; public class CheckedExceptionExample { public static void main(String[] args) { try { File file = new File("example.txt"); Scanner scanner = new Scanner(file); while (scanner.hasNextLine()) { System.out.println(scanner.nextLine()); } scanner.close(); } catch (FileNotFoundException e) { System.out.println("Error: File not found."); } } }
Output:
Error: File not found.
Example 2: Handling an Unchecked Exception
Here, we handle an ArithmeticException
.
public class UncheckedExceptionExample { public static void main(String[] args) { try { int result = 10 / 0; System.out.println("Result: " + result); } catch (ArithmeticException e) { System.out.println("Error: Division by zero."); } } }
Output:
Error: Division by zero.
Example 3: Using finally
This example shows how to use the finally
block to execute code regardless of whether an exception occurs.
public class FinallyExample { public static void main(String[] args) { try { int[] numbers = {1, 2, 3}; System.out.println(numbers[5]); } catch (ArrayIndexOutOfBoundsException e) { System.out.println("Error: Array index out of bounds."); } finally { System.out.println("Execution complete."); } } }
Output:
Error: Array index out of bounds. Execution complete.
Conclusion
The Exception
class in Java is crucial for handling errors and exceptions in a controlled manner. By using try-catch blocks and managing exceptions effectively, you can create robust and error-resistant Java applications.