Exception handling in Java is a mechanism to handle runtime errors so that the normal flow of a program is not interrupted.
Types of Exceptions in Java
✅ Checked Exception (Compile-time Exception)
Must be handled at compile time.
Example: IOException
, SQLException
.
⚠️ Unchecked Exception (Runtime Exception)
Occurs at runtime and is not mandatory to handle.
Example: NullPointerException
, ArithmeticException
.
❌ Error
Cannot be handled by the program.
Example: OutOfMemoryError
, StackOverflowError
.
🔑 Key Exception Handling Constructs
🔹 try
A block of code where an exception may occur.
🔹 catch
A block to handle exceptions.
🔹 finally
This block will execute whether an exception occurs or not.
🔹 throws
Used in method signatures to declare exceptions that may be thrown.
🔹 throw
Used to explicitly throw an exception.
🎯 Class Hierarchy:
- Checked Exception:
extends Exception
- Unchecked Exception:
extends RuntimeException
📌 Java Code Snippets
1️⃣ Try-Catch Example
📌 Description: Demonstrates handling exceptions with a try-catch
block.
try {
int x = 10;
int y = 0;
int result = x / y; // This will throw an ArithmeticException
} catch (ArithmeticException e) {
System.out.println("Cannot divide by zero!");
}
2️⃣ Custom Exception Handling Example
📌 Description: Demonstrates creating and using custom exceptions.
class InvalidAgeException extends Exception {
public InvalidAgeException(String message) {
super(message);
}
}
void validateAge(int age) throws InvalidAgeException {
if (age < 18) {
throw new InvalidAgeException("Age must be 18 or older");
}
}
3️⃣ Finally Block Execution Example
📌 Description: The finally
block executes even if an exception occurs.
try {
System.out.println(10 / 0);
} catch (ArithmeticException e) {
System.out.println("Exception caught");
} finally {
System.out.println("Finally block executed");
}
❓ Interview Questions
1️⃣ What is Exception Handling in Java?
📌 Answer: Exception handling is a mechanism to handle runtime errors, ensuring the normal flow of a program.
2️⃣ What is the difference between throw
and throws
?
📌 Answer:
throw
: Used inside a method to explicitly throw an exception.throws
: Declares exceptions that may be thrown by a method.
Example:
void check(int age) throws InvalidAgeException {
if (age < 18) {
throw new InvalidAgeException("Underage!");
}
}
3️⃣ What happens if an exception is not caught?
📌 Answer: If an exception is not caught, the JVM terminates the program and prints the stack trace.
🔹 Important Notes:
- If you have a
return
statement inside atry
block, thefinally
block will still execute. System.exit(0);
prevents thefinally
block from executing.
Leave a Reply