DEV Community

PONVEL M
PONVEL M

Posted on

Exception Handling in Java (Simple Explanation)

Introduction

While writing programs, errors can happen at any time. These errors can crash the program and stop it suddenly. In Java, we use Exception Handling to handle these errors and keep the program running smoothly.


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 invalid array index
  • Trying to open a file that doesn’t exist

Why Exception Handling is Important?

  • Prevents program crash
  • Maintains normal program flow
  • Improves user experience
  • Helps in debugging errors

Types of Exceptions

1. Checked Exception

  • Checked at compile time
  • Example: File handling errors

2. Unchecked Exception

  • Occurs at runtime
  • Example: ArithmeticException, NullPointerException

Basic Keywords in Exception Handling

1. try

Used to write code that may cause an exception.

2. catch

Used to handle the exception.

3. finally

Always executes (whether exception occurs or not).

4. throw

Used to manually throw an exception.

5. throws

Used to declare exceptions in method signature.


Simple Example

public class Example {
    public static void main(String[] args) {
        try {
            int a = 10;
            int b = 0;
            int result = a / b; // error
            System.out.println(result);
        } catch (ArithmeticException e) {
            System.out.println("Cannot divide by zero!");
        } finally {
            System.out.println("Program finished.");
        }
    }
}
Enter fullscreen mode Exit fullscreen mode

How it Works

  • try block contains risky code
  • If error occurs β†’ catch block runs
  • finally block runs always

Common Exceptions in Java

  • ArithmeticException
  • NullPointerException
  • ArrayIndexOutOfBoundsException
  • NumberFormatException

Advantages of Exception Handling

  • Keeps program stable
  • Handles runtime errors
  • Separates error-handling code from normal code
  • Makes code readable and maintainable

Conclusion

Exception Handling in Java is a powerful feature that helps developers manage errors effectively. Instead of stopping the program, it allows us to handle problems gracefully and continue execution.


My Learning Experience

While learning exception handling, I understood how important it is to manage errors properly. Using try and catch, I can control program crashes and make applications more reliable. It made my coding more professional and clean.


Top comments (0)