DEV Community

Kesavarthini
Kesavarthini

Posted on

Exception Handling in Java

What is Exception Handling?

Exception handling is a mechanism in Java that allows us to handle runtime errors so the program does not terminate abruptly.

It helps to:

  • Prevent program crash
  • Maintain normal flow
  • Improve user experience

What is an Exception?

An exception is an unwanted event that occurs during program execution and disrupts the normal flow of the program.

Example:

  • Dividing a number by zero
  • Accessing an invalid array index
  • Opening a file that doesn’t exist

Types of Exceptions in Java

Java exceptions are mainly divided into:

1️⃣ Checked Exceptions

  • Checked at compile time
  • Must be handled
  • Example: IOException, SQLException

2️⃣ Unchecked Exceptions

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

⚙️ Exception Handling Keywords

Java provides 5 main keywords:

  • try
  • catch
  • finally
  • throw
  • throws

Basic Syntax

try {
    // risky code
} catch (ExceptionType e) {
    // handling code
} finally {
    // always executes
}
Enter fullscreen mode Exit fullscreen mode

1️⃣ try Block

The try block contains the risky code — code that may cause an exception.

👉 If an exception occurs inside try, it will immediately stop executing and jump to catch block.

2️⃣ catch Block

The catch block handles the exception.

👉 It prevents the program from crashing.

If exception occurs:

  • Control moves from try → catch
  • Error is handled
  • Program continues

3️⃣ finally Block

The finally block always executes.

👉 Whether exception occurs or not
👉 Whether catch handles it or not

Used for:

  • Closing files
  • Closing database connections
  • Cleaning resources

Example: Handling ArithmeticException

public class Main {
    public static void main(String[] args) {

        try {
            int a = 10;
            int b = 0;
            int result = a / b;
            System.out.println(result);
        } catch (ArithmeticException e) {
            System.out.println("Cannot divide by zero!");
        }

        System.out.println("Program continues...");
    }
}
Enter fullscreen mode Exit fullscreen mode

Difference Between throw and throws

throw

  • Used inside method
  • Throws single exception
  • Followed by object

throws

  • Used in method declaration
  • Declares multiple exceptions
  • Followed by class name

Example:

throw new ArithmeticException("Error");
Enter fullscreen mode Exit fullscreen mode
void test() throws IOException {
}
Enter fullscreen mode Exit fullscreen mode

What Happens If Exception Is Not Handled?

If an exception is not handled:

  • Program terminates immediately
  • JVM prints stack trace
  • Remaining code will not execute
  • This is called abnormal termination.

Top comments (0)