Exceptions in Java
Exceptions in Java
Exceptions in Java are events that disrupt the normal flow of a program's
execution. They usually occur due to runtime errors like dividing by zero,
accessing an invalid index, or opening a file that doesn't exist.
✅ Key Concepts
🔹 What is an Exception?
⚙️Types of Exceptions
1. Checked Exceptions
Handled at compile time. If not handled, the program will not compile.
Examples:
• IOException
• SQLException
java
CopyEdit
import java.io.*;
Examples:
• ArithmeticException
• NullPointerException
• ArrayIndexOutOfBoundsException
java
CopyEdit
public class DivideExample {
public static void main(String[] args) {
int a = 10, b = 0;
int c = a / b; // ArithmeticException: / by zero
System.out.println(c);
}
}
📦 Exception Hierarchy
php
CopyEdit
Throwable
├── Error (serious problems, not caught by programs)
└── Exception
├── Checked (e.g., IOException)
└── Unchecked (RuntimeException)
🔸 try-catch Example
java
CopyEdit
public class TryCatchExample {
public static void main(String[] args) {
try {
int a = 10 / 0;
} catch (ArithmeticException e) {
System.out.println("Cannot divide by zero!");
}
}
}
🔸 finally Block
java
CopyEdit
public class ThrowExample {
public static void main(String[] args) {
throw new ArithmeticException("Manually thrown
exception");
}
}
🔹 throws
java
CopyEdit
public void readFile() throws IOException {
FileReader file = new FileReader("data.txt");
}
Custom Exceptions
You can create your own exception class by extending Exception or
RuntimeException.
java
CopyEdit
class MyException extends Exception {
public MyException(String message) {
super(message);
}
}
public class CustomExample {
public static void main(String[] args) {
try {
throw new MyException("Custom exception
thrown");
} catch (MyException e) {
System.out.println(e.getMessage());
}
}
}
✅ Best Practices
• Catch specific exceptions instead of generic ones.