An object that describes an unusual or erroneous situation
Exception handling
1. Ignore it (possible only with "unchecked" exception – abnormal termination)
2. Handle it where it occurs
3. Handle it in another place in the program
Java has a predefined set of exceptions and errors that can occur during execution
Error
Represents an unrecoverablesituation and should not be caught
try statement
Line that throws the exception is executed within a try block
A try block is followed by one or more catch clauses
Each catch clause has an associated exception type and is called an exception handler
When an exception occurs, processing continues at the first catch clause that matches the exception type
finally clause
Statements in the finallyclause always are executed
If no exception is generated, the statements in the finallyclause are executed after the statements in the try block complete
If an exception is generated, the statements in the finallyclause are executed after the statements in the appropriate catchclause complete
Exception class hierarchy
All error and exception classes are descendants of the Throwable class
A programmer can define an exception by extending the Exception class or one of its descendants
The parent class used depends on how the new exception will be used
Checked exceptions
Must be explicitly handled by the programmer
Compile-time exceptions that extend the Exception class (except RuntimeException and its subclasses)
Forced handling: The compiler ensures that you either handle them using try-catch blocks or declare them in the method signature using the throws keyword
Unchecked exceptions
Do not need explicit handling
Run-time exceptions that extend the RuntimeException class