π Introduction
While writing programs, errors are inevitable. These errors may occur due to invalid input, file issues, network problems, or logical mistakes. If not handled properly, they can cause your program to crash unexpectedly. β
π This is where Exception Handling in Java comes into play.
Exception handling allows us to:
- Prevent program crashes π₯
- Handle errors gracefully π
- Maintain normal program flow π
π§ What is an Exception?
π An exception is an unwanted or unexpected event that occurs during program execution.
π Example:
int a = 10 / 0; // ArithmeticException
π This will crash the program unless handled.
β οΈ Types of Errors in Java
πΉ 1. Compile-Time Errors β
- Detected during compilation
- Example: syntax errors
πΉ 2. Runtime Errors (Exceptions) β‘
- Occur during execution
- Example: divide by zero
πΉ 3. Logical Errors π€―
- Program runs but gives wrong output
π§© Types of Exceptions in Java
πΉ 1. Checked Exceptions β
π Checked at compile time
Examples:
- IOException
- SQLException
π Must be handled using try-catch OR declared using throws
πΉ 2. Unchecked Exceptions β
π Occur at runtime
Examples:
- ArithmeticException
- NullPointerException
- ArrayIndexOutOfBoundsException
πΉ 3. Errors (Serious Issues) π
Examples:
- OutOfMemoryError
- StackOverflowError
π Usually not handled
π Exception Handling Keywords in Java
| Keyword | Purpose |
|---|---|
| try | Wrap risky code |
| catch | Handle exception |
| finally | Always executes |
| throw | Manually throw exception |
| throws | Declare exception |
π§± 1. try-catch Block
β Complete Program
public class TryCatchDemo {
public static void main(String[] args) {
try {
int result = 10 / 0; // risky code
System.out.println(result);
} catch (ArithmeticException e) {
System.out.println("Cannot divide by zero!");
}
System.out.println("Program continues...");
}
}
π Explanation:
tryβ contains risky codecatchβ handles exception- Program does NOT crash β
π§± 2. Multiple catch Blocks
β Complete Program
public class MultipleCatchDemo {
public static void main(String[] args) {
try {
int[] arr = new int[3];
arr[5] = 10; // ArrayIndexOutOfBoundsException
int x = 10 / 0; // ArithmeticException
}
catch (ArrayIndexOutOfBoundsException e) {
System.out.println("Array index issue!");
}
catch (ArithmeticException e) {
System.out.println("Arithmetic error!");
}
}
}
π Explanation:
- Only one exception is handled at a time
- First matching catch block executes
π§± 3. Nested try-catch
β Complete Program
public class NestedTryDemo {
public static void main(String[] args) {
try {
try {
int x = 10 / 0;
} catch (ArithmeticException e) {
System.out.println("Inner catch handled division error");
}
int[] arr = new int[2];
arr[5] = 10;
} catch (ArrayIndexOutOfBoundsException e) {
System.out.println("Outer catch handled array error");
}
}
}
π Explanation:
- Inner try handles first exception
- Outer try handles remaining
π§± 4. finally Block
β Complete Program
public class FinallyDemo {
public static void main(String[] args) {
try {
int x = 10 / 0;
} catch (ArithmeticException e) {
System.out.println("Exception handled");
} finally {
System.out.println("This always executes");
}
}
}
π Key Point:
π finally ALWAYS runs (except system crash)
π§± 5. throw Keyword
β Complete Program
public class ThrowDemo {
public static void main(String[] args) {
int age = 15;
if (age < 18) {
throw new ArithmeticException("Not eligible to vote");
}
System.out.println("You can vote");
}
}
π Explanation:
- Used to manually throw exception
- Useful for validation
π§± 6. throws Keyword
β Complete Program
import java.io.*;
public class ThrowsDemo {
public static void readFile() throws IOException {
FileReader file = new FileReader("test.txt");
BufferedReader br = new BufferedReader(file);
System.out.println(br.readLine());
}
public static void main(String[] args) {
try {
readFile();
} catch (IOException e) {
System.out.println("File not found!");
}
}
}
π Explanation:
throwsdelegates exception handling to caller
π§± 7. Custom Exception
β Complete Program
class MyException extends Exception {
public MyException(String message) {
super(message);
}
}
public class CustomExceptionDemo {
public static void main(String[] args) {
try {
int balance = 500;
if (balance < 1000) {
throw new MyException("Insufficient balance!");
}
} catch (MyException e) {
System.out.println(e.getMessage());
}
}
}
π Explanation:
- Create your own exception
- Useful in real-world applications
β οΈ Common Mistakes Students Make
β 1. Using catch without try
catch(Exception e) {} // β invalid
β 2. Catching generic Exception unnecessarily
catch(Exception e) // bad practice sometimes
β 3. Ignoring finally block
π Important for resource closing
β 4. Not handling checked exceptions
π Leads to compile-time error
β 5. Writing unreachable catch blocks
catch(Exception e)
catch(ArithmeticException e) // β unreachable
π€― Common Confusions
π€ Difference between throw vs throws
| throw | throws |
|---|---|
| Used inside method | Used in method signature |
| Throws one exception | Declares multiple |
π€ finally vs finalize()
finallyβ blockfinalize()β method (GC related)
πΌ Interview Questions
β What is exception handling?
π Mechanism to handle runtime errors.
β Difference between checked and unchecked?
π Checked β compile-time
π Unchecked β runtime
β Can we have try without catch?
π Yes (with finally)
β Can finally not execute?
π Yes (System.exit())
β What is custom exception?
π User-defined exception class
π― Best Practices
βοΈ Catch specific exceptions
βοΈ Use finally for cleanup
βοΈ Avoid empty catch blocks
βοΈ Use custom exceptions when needed
π Conclusion
Exception handling is a fundamental concept in Java that ensures your program runs smoothly even when errors occur. π
In this blog, you learned:
- βοΈ Types of exceptions
- βοΈ try, catch, finally, throw, throws
- βοΈ Custom exceptions
- βοΈ Common mistakes & interview questions
π‘ Final Thought
π Writing code is not just about making it work β
π Itβs about making it robust and error-resistant πͺ
π₯ One-Line Summary
π βException handling allows a program to handle errors gracefully without crashing.β
π» Happy Coding! π
Master exception handling β it’s one of the most asked topics in interviews π―