Java Tutorial

Operators

Flow Control

String

Number and Date

Built-in Classes

Array

Class and Object

Inheritance and Polymorphism

Exception Handling

Collections, Generics and Enumerations

Reflection

Input/Output Stream

Annotation

Java Exception Handling Mechanism And Basic Structure Of Exception Handling

In Java, exception handling is a mechanism that allows you to handle errors or unexpected events that occur during program execution. The basic structure of exception handling in Java involves three keywords: try, catch, and finally.

Here is the basic structure of exception handling in Java:

try {
    // Block of code to try
} catch (ExceptionType1 e1) {
    // Block of code to handle ExceptionType1
} catch (ExceptionType2 e2) {
    // Block of code to handle ExceptionType2
} finally {
    // Block of code to be executed regardless of whether an exception was thrown or not
}

In this structure, the try block contains the code that might throw an exception. If an exception is thrown, the program jumps to the appropriate catch block that matches the type of the exception.

Each catch block handles a specific type of exception, and can contain code to handle the exception or provide information about the error.

The finally block is executed regardless of whether an exception was thrown or not, and can be used to release resources or perform cleanup tasks.

Here is an example of using the try-catch-finally structure to handle exceptions in Java:

import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        try {
            File file = new File("input.txt");
            Scanner scanner = new Scanner(file);
            System.out.println(scanner.nextLine());
            scanner.close();
        } catch (FileNotFoundException e) {
            System.out.println("File not found: " + e.getMessage());
        } finally {
            System.out.println("End of program");
        }
    }
}

In this example, we define a try-catch-finally block that attempts to read the first line of a file called input.txt. If the file is not found, an exception of type FileNotFoundException is thrown. The catch block catches this exception and prints out an error message. The finally block is executed regardless of whether an exception was thrown or not, and prints out a message indicating the end of the program.

Overall, the try-catch-finally structure is an important part of Java exception handling, allowing you to handle errors and unexpected events in a controlled and reliable manner.

  1. Basic structure of exception handling in Java

    Exception handling in Java involves using try, catch, and finally blocks. The basic structure is:

    try {
        // Code that may throw an exception
    } catch (ExceptionType ex) {
        // Handle the exception
    } finally {
        // Code to execute regardless of whether an exception occurred
    }
    
  2. try-catch blocks in Java exception handling

    The try block contains the code that might throw an exception. The catch block handles the exception and provides an opportunity for custom error handling.

    try {
        // Code that may throw an exception
    } catch (ExceptionType ex) {
        // Handle the exception
    }
    
  3. Throwing and catching exceptions in Java

    Exceptions can be thrown using the throw keyword, and they are caught using catch blocks.

    try {
        throw new Exception("This is an example exception");
    } catch (Exception e) {
        System.out.println("Caught exception: " + e.getMessage());
    }
    
  4. Java finally block and its role in exception handling

    The finally block contains code that always executes, whether an exception occurred or not. It is useful for cleanup operations.

    try {
        // Code that may throw an exception
    } catch (ExceptionType ex) {
        // Handle the exception
    } finally {
        // Code to execute regardless of whether an exception occurred
    }
    
  5. Checked and unchecked exceptions in Java

    Checked exceptions are checked at compile time and must be caught or declared. Unchecked exceptions (RuntimeExceptions) do not require explicit handling.

    // Checked exception (must be caught or declared)
    try {
        throw new IOException();
    } catch (IOException e) {
        // Handle or declare
    }
    
    // Unchecked exception
    throw new RuntimeException();
    
  6. Nested try-catch blocks in Java

    Exception handling can be nested with multiple try-catch blocks, allowing for fine-grained error handling.

    try {
        try {
            // Nested try block
        } catch (ExceptionType ex) {
            // Handle the exception
        }
    } catch (AnotherExceptionType ex) {
        // Handle another exception
    }
    
  7. Exception hierarchy in Java

    Exceptions in Java are organized in a hierarchy. Exception is the superclass, and more specific exception types inherit from it.

    try {
        // Code that may throw an exception
    } catch (Exception ex) {
        // Handle the exception (can catch any exception type)
    }
    
  8. Custom exception classes in Java

    You can create custom exception classes by extending the Exception class, providing a more specific exception type for your application.

    class CustomException extends Exception {
        // Custom exception code
    }
    
    try {
        throw new CustomException();
    } catch (CustomException e) {
        // Handle custom exception
    }