DEV Community

Hayes vincent
Hayes vincent

Posted on

Exception Handling Keywords in Java

πŸ“Œ What is an Exception?

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

πŸ” Common Examples:
Dividing a number by zero
Accessing a null object
Trying to open a file that doesn’t exist

  1. try Block

The try block is used to wrap code that might throw an exception.

 Syntax:
try {
    // risky code
}
 Example:
try {
    int a = 10 / 0; // Exception occurs
}
Enter fullscreen mode Exit fullscreen mode

Where is it used?
Database operations
File handling
Network calls

  1. catch Block

The catch block handles the exception thrown inside the try block.

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

Where is it used?
Displaying user-friendly error messages
Preventing program crashes

  1. finally Block

The finally block always executes, whether an exception occurs or not.

 Syntax:
finally {
    // cleanup code
}
 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 Usage:
Closing database connections
Closing files
Releasing system resources

  1. throw Keyword

The throw keyword is used to manually throw an exception.

Syntax:
throw new Exception("message");
 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 is it used?
Custom validations
Business rules (e.g., age restrictions)

  1. throws Keyword

The throws keyword is used in method signatures to declare exceptions.

Syntax:
void method() throws Exception {
    // code
}
 Example:
import java.io.*;

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

Where is it used?
File handling
Checked exceptions
Passing responsibility to the caller

** Conclusion**

Exception handling in Java helps you build robust and error-free applications. By using try, catch, finally, throw, and throws, you can manage errors effectively and ensure smooth program execution.

Top comments (0)