What is an Exception?
An exception is an unwanted event that occurs during program execution.
Example:
Dividing a number by zero
Accessing null object
File not found
1. try Block
The try block contains code that may cause an exception.
Syntax:
try {
// risky code
}
Example:
try {
int a = 10 / 0; // exception
}
Where we use:
--> Database operations
--> File handling
--> Network calls
2. catch Block
The catch block handles the exception thrown in the try.
Syntax:
catch(Exception e) {
// handling code
}
Example:
try {
int a = 10 / 0;
} catch (ArithmeticException e) {
System.out.println("Cannot divide by zero");
}
Where we use:
--> To show user-friendly messages
--> To prevent program crash
3. finally Block
The finally block always executes whether an exception occurs or not.
Syntax:
finally {
// cleanup code
}
Example:
try {
int a = 10 / 2;
} catch (Exception e) {
System.out.println("Error");
} finally {
System.out.println("Always executed");
}
Real-time use:
--> Closing database connection
--> Closing files
--> Releasing resources
4.throw Keyword
Used to manually throw an exception.
Syntax:
throw new Exception("message");
Example:
public class Main {
public static void main(String[] args) {
int num = -5;
if (num < 0) {
throw new ArithmeticException("Negative number not allowed");
}
System.out.println("Valid number");
}
}
Where we use:
--> Custom validations
--> Business rules (e.g., age restriction)
5. throws Keyword
Used to declare exceptions in method signature.
Syntax:
void method() throws Exception {
// code
}
Example:
import java.io.*;
class Test {
void readFile() throws IOException {
FileReader file = new FileReader("test.txt");
}
}
Where we use:
--> File handling
--> Checked exceptions
--> Passing responsibility to caller
Top comments (0)