DEV Community

Vidya
Vidya

Posted on

Exception Handling Keywords in Java

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
 }
Enter fullscreen mode Exit fullscreen mode

Example:

try {
    int a = 10 / 0; // exception
}
Enter fullscreen mode Exit fullscreen mode

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
   }
Enter fullscreen mode Exit fullscreen mode

Example:

try {
    int a = 10 / 0;
} catch (ArithmeticException e) {
    System.out.println("Cannot divide by zero");
}
Enter fullscreen mode Exit fullscreen mode

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
   }
Enter fullscreen mode Exit fullscreen mode

Example:

try {
    int a = 10 / 2;
} catch (Exception e) {
    System.out.println("Error");
} finally {
    System.out.println("Always executed");
}

Enter fullscreen mode Exit fullscreen mode

Real-time use:
--> Closing database connection
--> Closing files
--> Releasing resources

4.throw Keyword
Used to manually throw an exception.

Syntax:
     throw new Exception("message");
Enter fullscreen mode Exit fullscreen mode

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");
    }
}

Enter fullscreen mode Exit fullscreen mode

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
  }
Enter fullscreen mode Exit fullscreen mode

Example:

import java.io.*;

class Test {
    void readFile() throws IOException {
        FileReader file = new FileReader("test.txt");
    }
}

Enter fullscreen mode Exit fullscreen mode

Where we use:
--> File handling
--> Checked exceptions
--> Passing responsibility to caller

Top comments (0)