PROJECTENGRAM

EXCEPTION HANDLING

Exception Handling

Tags: #◇Computer Science #◇CCPROG3 #◇Exception Handling #◇Code Snippets #◇M9


◇Key Definitions

Exception Handling is a mechanism to handle runtime errors, ensuring the normal flow of the application can be maintained.

◇Theoretical Framework

In Java, exceptions are objects that wrap an error event that occurred within a method. Checked Exceptions: Checked at compile-time (e.g., IOException). Must be declared or handled. Unchecked Exceptions: Runtime exceptions (e.g., NullPointerException). Not checked at compile-time. Errors: Serious problems that a reasonable application should not try to catch (e.g., OutOfMemoryError).

◇Code Implementation

『』
JAVA
import java.io.*;

public class ExceptionExample {
    public static void main(String[] args) {
        try {
            int result = 10 / 0; // Throws ArithmeticException
        } catch (ArithmeticException e) {
            System.out.println("Cannot divide by zero!");
        } finally {
            System.out.println("This block always executes.");
        }
    }
    
    // Method declaring a checked exception
    public void readFile(String path) throws IOException {
        FileReader file = new FileReader(path);
        BufferedReader fileInput = new BufferedReader(file);
        
        // Print first 3 lines
        for (int counter = 0; counter < 3; counter++) 
            System.out.println(fileInput.readLine());
            
        fileInput.close();
    }
}

◇Syntax Breakdown

try: Defines a block of code to be tested for errors. catch: Defines a block of code to be executed if an error occurs. finally: Defines a block of code to be executed regardless of the result. throw: Used to throw an exception explicitly. throws: Used in a method signature to declare that it might throw exceptions.

◇Complexity Analysis

Exception handling introduces slight runtime overhead during the normal execution flow and significant overhead when an exception is actually thrown and caught, due to stack trace generation and stack unwinding. Avoid using exceptions for normal control flow.

◇References & Navigation

CONFIRMATION // 理解度の確認

ACTIVE RECALL VERIFICATION

Select an answer to verify conceptual comprehension and reveal the technical rationale.

Q1

What is the primary purpose of Exception Handling in Java?

Q2

How do Checked Exceptions differ from Unchecked Exceptions?

Q3

Which block of code executes regardless of whether an exception occurs or not?

Q4

What does the throws keyword indicate when used in a method signature?

Q5

Why is it recommended to avoid using exceptions for normal control flow?

Exception Handling | PROJECT ENGRAM