DEV Community

KIRAN RAJ
KIRAN RAJ

Posted on

Exception Handling In Java(Complete Guide with Examples)

Exception Handling in Java

- Introduction

Exception handling is a powerful mechanism in Java that helps developers manage runtime errors and maintain the normal flow of applications. Instead of crashing the program, Java allows you to handle unexpected situations gracefully using structured blocks like try, catch, and finally.


1.What is an Exception?

An exception is an error that occurs during the execution of a program (runtime error).

👉 Example:

int a = 10;
int b = 0;
int c = a / b; // ArithmeticException


2.Types of Exceptions

✅ Checked Exceptions

  • Checked at compile time
  • Must be handled using try-catch or throws
  • Example: IOException, SQLException

❌ Unchecked Exceptions

  • Occur at runtime
  • Not mandatory to handle
  • Example: NullPointerException, ArithmeticException

3.Important Keywords

  1. try

Wraps code that may cause an exception.

  1. catch

Handles the exception.

  1. finally

Always executes (except when JVM stops).

  1. throw

Used to explicitly throw an exception.

  1. throws

Declares exceptions in a method signature.


4.Order of Execution

Correct order:

try → catch → finally


5.Common Exceptions

  • Divide by zero → ArithmeticException
  • Null value access → NullPointerException
  • Invalid array index → ArrayIndexOutOfBoundsException

6.Exception Propagation

Exception propagation means passing an exception from one method to another until it is handled.

void method1() {
    int x = 10 / 0;
}

void method2() {
    method1();
}

void method3() {
    try {
        method2();
    } catch (Exception e) {
        System.out.println("Handled");
    }
}
Enter fullscreen mode Exit fullscreen mode

Code Examples

7.Handling Exception

try {
    int x = 10 / 0;
} catch (ArithmeticException e) {
    System.out.println("Error");
}

Enter fullscreen mode Exit fullscreen mode

8.Null Handling

try {
    String s = null;
    System.out.println(s.length());
} catch (Exception e) {
    System.out.println("Handled");
}
Enter fullscreen mode Exit fullscreen mode

9.Throw Example

if(marks < 0 || marks > 100){
    throw new IllegalArgumentException("Invalid marks");
}
Enter fullscreen mode Exit fullscreen mode

10.SpecialCase:System.exit()

try {
    System.exit(0);
} finally {
    System.out.println("Finally");
}
Enter fullscreen mode Exit fullscreen mode
Output: Finally will NOT execute
Enter fullscreen mode Exit fullscreen mode

Reason: JVM stops immediately.


11. Purpose of Finally Block

Used for cleanup operations:

Closing files

Releasing resources

Closing database connections


12.Important Rules

try cannot exist alone

Must be followed by catch or finally

catch blocks must be ordered from specific → general

Parent class (Exception) should come last


13.Quick Summary

Exception = Runtime error

try-catch = Handle errors

finally = Cleanup

throw = Create exception

throws = Declare exception

Propagation = Passing exception to caller


14.Conclusion

Exception handling is essential for building robust Java applications. By using proper handling techniques, developers can prevent crashes, improve user experience, and write clean, maintainable code.

Top comments (0)