An exception is an event, which occurs during the execution of a program, that disrupts the normal flow of the program's instructions.
When an error occurs within a method, the method creates an object and hands it off to the runtime system. The object, called an exception object, contains information about the error, including its type and the state of the program when the error occurred. Creating an exception object and handing it to the runtime system is called throwing an exception.
An exception object is created when an exception is thrown and is passed to the catch block much like an parameter to a method :
The exception object is passed to the code designated to catch the exception, which may then use methods of the exception object to help handle the situation. Occurrence of an exception generates an object containing information about the exception.
There is an API class called Exception another class, Error, also inherits from Throwable all exception classes inherit from Exception, which inherits from Throwable your code must handle most exceptions, but generally should not attempt to handle Error subtypes(like OutOfMemoryError or stackOverflowError).
Checked and Unchecked Exceptions :
Anything from a runtime exception is an unchecked exception. Meaning you don't have to provided a try/catch block. Subclasses of Error or RuntimeException.
Key Points About Exceptions:
- Be specific while handling the exception in your catch block.
- Be specific while throwing exception in your throws clause.
- Do not use Exception Handling to control programming flow.
- Very little overhead is imposed by using exception handling mechanism unless an exception occurs or thrown a new exception object explicitly.
- Always use the finally block to release the resources to prevent resource leaks.
- Handle exceptions locally wherever possible.
- Do not use Exception handling in loops
Sample Code :
try {
/ / Read data from a file on disk
DataInputStream fl = new DataInputStream( new FileInputStream("data.dat"));
try {
/ / Process here
} finally {
/ / Close the streams
fl.close();
}
} catch (IOException e) {
/ / Process exceptions
e.printStackTrace();
}