1. What are Exceptions?
Exceptions are events that disrupt the normal flow of the program and can
occur during runtime. They represent errors or other exceptional conditions
that need to be handled.
Java uses try-catch blocks to handle exceptions.
There are two main types of exceptions in Java:
o Checked Exceptions: Exceptions that the compiler forces you to
handle (e.g., IOException, SQLException).
o Unchecked Exceptions: Exceptions that occur due to programming
errors, such as logical errors or improper use of APIs (e.g.,
NullPointerException, ArrayIndexOutOfBoundsException).
2. Try-Catch Block
A try block is used to wrap the code that might throw an exception.
A catch block handles the exception and prevents the program from
crashing.
Syntax:
try {
// Code that might throw an exception
} catch (ExceptionType e) {
// Handle the exception
}
Example:
public class Main {
public static void main(String[] args) {
try {
, int result = ; // ArithmeticException
} catch (ArithmeticException e) {
System.out.println("Cannot divide by zero!");
}
}
}
Important Points:
You can have multiple catch blocks for handling different types of
exceptions.
The catch block can catch specific types of exceptions or the generic
Exception class.
3. Finally Block
The finally block is optional and is used to execute code that must run
regardless of whether an exception occurs or not (e.g., closing files or
releasing resources).
It is executed after the try block, whether an exception is thrown or not.
Syntax:
try {
// Code that might throw an exception
} catch (ExceptionType e) {
// Handle the exception
} finally {
// Code to be executed after try-catch, like resource cleanup
}
Example:
public class Main {
public static void main(String[] args) {
try {
System.out.println("Trying to open a file...");