exception and exception handling in java

exception and exception handling in java

what is exception in java with example

In Java, an exception is an event that disrupts the normal flow of a program’s instructions during execution. Exceptions are used to handle errors and other exceptional events that can occur in a Java program. When an exceptional event occurs, an object representing that exception is created and thrown in the method that caused the error.

Here’s a basic overview of exceptions in Java:

1. Throwing an Exception: You can throw an exception explicitly using the throw keyword. For example, you might throw an exception if a certain condition is not met:

Exception Example
if(someConditionIsNotMet) {
    throw new Exception("This is an error message");
}

2. Catching an Exception: Exceptions are caught using try, catch, and finally blocks. Code that might throw an exception is enclosed within a try block, and if an exception occurs, it’s caught and handled in a corresponding catch block:

Catching an Exception using try catch block
try {
    // code that might cause an exception
} catch (Exception e) {
    // handle the exception
    System.out.println("An exception occurred: " + e.getMessage());
} finally {
    // code that will be executed regardless of whether an exception occurred or not
}

In the catch block, you can handle the exception, log the error, or take any necessary corrective action.

Types of Exceptions

Types of Exceptions: There are two main types of exceptions in Java: checked exceptions and unchecked exceptions.

  1. Checked Exceptions (Compile time Exceptions)
  2. Unchecked Exceptions (Runtime Exceptions)

1. Checked Exceptions: These are exceptions that are checked at compile-time. If a method is capable of causing a checked exception, it must declare that it throws the exception using the throws keyword.

Checked Exception example
public void readFile() throws IOException {
    // code that might throw IOException
}

2. Unchecked Exceptions (Runtime Exceptions): These are exceptions that are not checked at compile-time. They extend the RuntimeException class. Examples include NullPointerException, ArrayIndexOutOfBoundsException, etc. Methods are not required to declare that they may throw unchecked exceptions.

Unchecked Exception example
public void divide(int a, int b) {
    if (b == 0) {
        throw new ArithmeticException("Division by zero is not allowed");
    }
    int result = a / b;
    System.out.println("Result: " + result);
}

Unchecked exceptions are often caused by bugs in the code (such as trying to access an array element that doesn’t exist), while checked exceptions are usually related to external factors, like file I/O operations or network connections.

Custom Exceptions

Custom Exceptions: You can also create your own custom exceptions by extending the Exception class or any of its subclasses. Custom exceptions allow you to define specific exception types for your application.

Custom Exception example
class CustomException extends Exception {
    CustomException(String message) {
        super(message);
    }
}

And then you can throw and catch your custom exception like any other exception.

Exceptions in Java provide a way to handle errors and exceptional situations gracefully, allowing the program to recover or terminate without crashing. They are an essential part of Java’s error handling mechanism, ensuring robust and reliable applications.


what is exception handling in java with example

Exception handling in Java is a mechanism used to handle runtime errors (exceptions) gracefully, allowing the program to recover from unexpected situations without crashing. Java provides a robust exception handling mechanism through the use of try, catch, finally, throw, and throws keywords.

Basic Exception Handling Structure:
Basic Exception Handling example
try {
    // Code that might cause an exception
} catch (ExceptionType e) {
    // Code to handle the exception
} finally {
    // Code that will be executed regardless of whether an exception occurred or not
}

Here’s an explanation of the keywords and their roles:

  • try Block: The code that might throw an exception is placed inside the try block.
  • catch Block: If an exception occurs within the try block, it is caught and handled in the corresponding catch block. The catch block specifies the type of exception it can handle. You can have multiple catch blocks to handle different types of exceptions.
  • finally Block: The finally block contains code that will be executed regardless of whether an exception occurred or not. It is often used for cleanup tasks, such as closing files or releasing resources.
  • throw Keyword: The throw keyword is used to explicitly throw an exception. You can throw either a built-in exception or a custom exception.
  • throws Keyword: The throws keyword is used in method declarations to indicate that the method might throw certain exceptions. It notifies the caller that they need to handle those exceptions.

Example of Exception Handling:
Exception example
import java.util.InputMismatchException;
import java.util.Scanner;
/*
 * Author: Zameer Ali Mohil
 * */
public class ExceptionHandlingExample {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        try {
            System.out.print("Enter a number: ");
            int num = scanner.nextInt(); // This might cause an InputMismatchException
            int result = 10 / num; // This might cause an ArithmeticException
            System.out.println("Result: " + result);
        } catch (InputMismatchException e) {
            System.out.println("Invalid input. Please enter a number.");
        } catch (ArithmeticException e) {
            System.out.println("Cannot divide by zero.");
        } finally {
            System.out.println("This block always executes, regardless of exceptions.");
            scanner.close();
        }
    }
}

In this example:

  • The try block contains code that might throw InputMismatchException or ArithmeticException.
  • The catch blocks handle these exceptions and provide appropriate error messages.
  • The finally block closes the Scanner object, ensuring that it is always closed, even if an exception occurs.

Exception handling helps prevent program crashes due to unexpected situations, making Java programs more robust and reliable.

Leave a Reply

Your email address will not be published. Required fields are marked *