Spex3
    

Java Exception Handling


    

    

Java Exception Handling
Exception handling in Java is a mechanism to handle runtime errors and ensure smooth program execution.

1. What is an Exception?
An exception is an event that disrupts the normal flow of a program. It occurs due to errors like division by zero, invalid array index, or file not found.

Types of Exceptions
Exception Type Description Example
Checked Exception Compile-time exceptions IOException, SQLException
Unchecked Exception Runtime exceptions NullPointerException, ArithmeticException
Error Serious problems OutOfMemoryError, StackOverflowError

2. Handling Exceptions Using Try-Catch
The try-catch block allows us to handle exceptions gracefully without crashing the program.

✅ Example of Try-Catch


public class ExceptionExample {
public static void main(String[] args) {
try {
int result = 10 / 0; // This will cause an exception
System.out.println(result);
} catch (ArithmeticException e) {
System.out.println("Cannot divide by zero!");
}
System.out.println("Program continues...");
}
}


💡 Output:


Cannot divide by zero!
Program continues...
Multiple Catch Blocks
A try block can have multiple catch blocks to handle different exceptions.

✅ Example of Multiple Catch Blocks


public class MultipleCatchExample {
public static void main(String[] args) {
try {
int arr[] = {10, 20, 30};
System.out.println(arr[5]); // ArrayIndexOutOfBoundsException
} catch (ArithmeticException e) {
System.out.println("Arithmetic Exception occurred!");
} catch (ArrayIndexOutOfBoundsException e) {
System.out.println("Array Index Out of Bounds!");
} catch (Exception e) {
System.out.println("Some other exception occurred.");
}
}
}


💡 Output:


Array Index Out of Bounds!


3. Finally Block
The finally block always executes, whether an exception occurs or not. It is useful for closing resources like files and databases.

✅ Example of Finally Block


public class FinallyExample {
public static void main(String[] args) {
try {
int result = 10 / 2;
System.out.println(result);
} catch (Exception e) {
System.out.println("An error occurred.");
} finally {
System.out.println("Finally block executed.");
}
}
}


💡 Output:

5

Finally block executed.

4. Throwing Exceptions Using throw
The throw keyword allows you to manually throw an exception.

✅ Example of throw


public class ThrowExample {
static void checkAge(int age) {
if (age < 18) {
throw new ArithmeticException("Access denied – You must be 18 or older.");
} else {
System.out.println("Access granted – You are old enough.");
}
}

public static void main(String[] args) {
checkAge(15);
}
}


💡 Output:


Exception in thread "main" java.lang.ArithmeticException: Access denied – You must be 18 or older.

5. Creating Custom Exceptions
You can create your own exception class by extending the Exception class.

✅ Example of a Custom Exception


// Custom exception class
class InvalidAgeException extends Exception {
public InvalidAgeException(String message) {
super(message);
}
}

// Main class
public class CustomExceptionExample {
static void validateAge(int age) throws InvalidAgeException {
if (age < 18) {
throw new InvalidAgeException("You must be at least 18 years old.");
} else {
System.out.println("Valid age.");
}
}

public static void main(String[] args) {
try {
validateAge(16);
} catch (InvalidAgeException e) {
System.out.println("Exception caught: " + e.getMessage());
}
}
}


💡 Output:


Exception caught: You must be at least 18 years old.

Summary
✔ try-catch: Handles exceptions.
✔ Multiple catch blocks: Handle different exceptions.
✔ finally: Always executes.
✔ throw: Manually throws an exception.
✔ Custom exceptions: Create user-defined exceptions.