Monday, July 21, 2025

Java Learn Try Catch

# Java Try-Catch Blocks - Full Guide

Exception handling in Java is done using `try`, `catch`, `finally`, and `throw` statements. Here's a comprehensive guide to using these statements effectively.

## Basic Try-Catch Block

```java
try {
    // Code that might throw an exception
} catch (ExceptionType e) {
    // Code to handle the exception
}
```

### Example:
```java
try {
    int result = 10 / 0; // This will throw ArithmeticException
} catch (ArithmeticException e) {
    System.out.println("Cannot divide by zero!");
}
```

## Multiple Catch Blocks

```java
try {
    // Code that might throw different exceptions
} catch (ExceptionType1 e1) {
    // Handle ExceptionType1
} catch (ExceptionType2 e2) {
    // Handle ExceptionType2
}
```

### Example:
```java
try {
    int[] numbers = {1, 2, 3};
    System.out.println(numbers[5]); // ArrayIndexOutOfBoundsException
    int x = Integer.parseInt("abc"); // NumberFormatException
} catch (ArrayIndexOutOfBoundsException e) {
    System.out.println("Array index out of bounds!");
} catch (NumberFormatException e) {
    System.out.println("Invalid number format!");
}
```

## The Finally Block

```java
try {
    // Code that might throw an exception
} catch (ExceptionType e) {
    // Handle exception
} finally {
    // Code that always executes
}
```

### Example:
```java
FileReader reader = null;
try {
    reader = new FileReader("file.txt");
    // Read file
} catch (FileNotFoundException e) {
    System.out.println("File not found!");
} finally {
    if (reader != null) {
        try {
            reader.close(); // Always close the resource
        } catch (IOException e) {
            System.out.println("Error closing file");
        }
    }
}
```

## Try-With-Resources (Java 7+)

```java
try (ResourceType resource = new ResourceType()) {
    // Use resource
} catch (ExceptionType e) {
    // Handle exception
}
```

### Example:
```java
try (FileReader reader = new FileReader("file.txt")) {
    // Read file - resource will be automatically closed
} catch (FileNotFoundException e) {
    System.out.println("File not found!");
} catch (IOException e) {
    System.out.println("Error reading file");
}
```

## Exception Hierarchy

```
Throwable
├── Error (serious problems like OutOfMemoryError)
└── Exception
    ├── RuntimeException (unchecked exceptions)
    └── Other Exceptions (checked exceptions)
```

## Checked vs Unchecked Exceptions

1. **Checked Exceptions**: Must be declared or handled (e.g., IOException)
2. **Unchecked Exceptions**: Don't need to be declared (e.g., NullPointerException)

## Throwing Exceptions

```java
throw new ExceptionType("Error message");
```

### Example:
```java
public void setAge(int age) {
    if (age < 0) {
        throw new IllegalArgumentException("Age cannot be negative");
    }
    this.age = age;
}
```

## Custom Exceptions

```java
class MyException extends Exception {
    public MyException(String message) {
        super(message);
    }
}
```

### Example:
```java
try {
    throw new MyException("This is my custom exception");
} catch (MyException e) {
    System.out.println(e.getMessage());
}
```

## Best Practices

1. Catch specific exceptions before general ones
2. Don't catch `Throwable` or `Exception` unless necessary
3. Clean up resources in finally blocks or use try-with-resources
4. Include meaningful error messages
5. Don't use exceptions for normal flow control
6. Log exceptions before handling them

## Common Exception Types

1. `NullPointerException` - When you try to use a null reference
2. `ArrayIndexOutOfBoundsException` - Invalid array index
3. `ClassCastException` - Invalid type casting
4. `IllegalArgumentException` - Invalid method argument
5. `IOException` - Input/output operation failure
6. `FileNotFoundException` - File doesn't exist
7. `NumberFormatException` - Invalid number format

Would you like me to explain any specific aspect of Java exception handling in more detail?

No comments: