1. What are Exceptions in Java?
Exceptions in Java are errors that happen during runtime (program execution) which interrupt the
normal ow of the program.
Java handles exceptions using a powerful Exception Handling mechanism to avoid program
crashes and manage errors gracefully.
All exceptions come from the Throwable class. It has two main types:
• Checked Exceptions – Checked at compile time (e.g., IOException,
SQLException).
• Unchecked Exceptions – Checked at runtime (e.g., ArithmeticException,
NullPointerException).
We handle exceptions using:
• try – block where we write risky code.
• catch – block that handles the exception.
• finally – (optional) block that always executes.
• throw – used to throw an exception manually.
• throws – used to declare an exception in method signature.
2. Built-in and User-de ned Exceptions
Built-in Exceptions:
These are prede ned exception classes in Java. Common examples:
• ArithmeticException – when dividing by zero.
• NullPointerException – when accessing an object with null reference.
• ArrayIndexOutOfBoundsException – when array index is out of range.
fl
fi
fi
Example:
public class Example {
public static void main(String[] args) {
try {
int x = 10 / 0; // ArithmeticException
} catch (ArithmeticException e) {
System.out.println("Error: " + e.getMessage());
}
}
}
User-de ned Exceptions:
These are exceptions created by the programmer for custom error handling.
To create one:
• Extend the Exception class.
• Create a constructor with a message.
Example:
class MyException extends Exception {
public MyException(String msg) {
super(msg);
}
}
3. Java Program: Custom Exception InvalidAgeException
This program throws a custom exception if the user's age is less than 18.
// Step 1: Create custom exception
class InvalidAgeException extends Exception {
public InvalidAgeException(String message) {
super(message);
}
}
// Step 2: Main class
public class AgeCheck {
// Method to validate age
public static void checkAge(int age) throws
InvalidAgeException {
if (age < 18) {
throw new InvalidAgeException("Age must be 18 or
above.");
} else {
System.out.println("Valid age. Access granted.");
}
}
fi
public static void main(String[] args) {
int age = 16; // Example age
try {
checkAge(age);
} catch (InvalidAgeException e) {
System.out.println("Exception: " + e.getMessage());
}
}
}
Output:
Exception: Age must be 18 or above.