As a software engineer, I believe that real learning begins when students start asking *why*. The FAQ below addresses not just definitions, but also the reasoning behind Java’s design. Understanding these ensures you can handle errors like a professional developer, not just a student.
An Exception is an event that disrupts the normal execution flow of a program. Exception handling allows developers to catch and handle such runtime events gracefully, maintaining application stability.
IOException).NullPointerException).
// Example
try {
FileReader fr = new FileReader("file.txt");
} catch(IOException e) {
System.out.println("Checked exception handled.");
}
try — Monitor risky codecatch — Handle the exceptionfinally — Execute cleanup codethrow — Manually raise exceptionthrows — Declare exception propagation
try {
int num = 10 / 0;
} catch (ArithmeticException e) {
System.out.println("Division by zero!");
} finally {
System.out.println("Cleanup code runs here.");
}
throw — Used to raise a specific exception instance.throws — Declares possible exceptions for a method.
void validate(int age) throws Exception {
if(age < 18)
throw new Exception("Underage");
}
No. A try must be followed by either catch or finally (or both).
System.exit() is invoked.
Throwable
├── Error
│ ├── OutOfMemoryError
│ └── StackOverflowError
└── Exception
├── IOException (Checked)
├── SQLException (Checked)
└── RuntimeException (Unchecked)
├── NullPointerException
├── ArithmeticException
└── ArrayIndexOutOfBoundsException
class InvalidAgeException extends Exception {
InvalidAgeException(String msg) {
super(msg);
}
}
When an exception is not handled in one method, it propagates to the calling method. This continues until caught or until the JVM terminates the program.
Throwable.throw is for raising, throws for declaring exceptions.By mastering these fundamentals, you can confidently handle any exception scenario in professional Java applications.