An Exception is an unwanted event that interrupts the normal flow of the program. When an exception occurs program execution gets terminated. In such cases, we get a system-generated error message. However, the exception can be handled in Java. By handling the exceptions, we can provide a meaningful message to the user about the issue rather than a system-generated message, which may not be understandable by the user.
Exception handling ensures that the flow of the program doesn't break when an exception occurs. For example, if a program has a bunch of statements and an exception occurs midway after executing certain statements then the statements after the exception will not be executed and the program will terminate abruptly.
By handling we make sure that all the statements execute and the flow of the program doesn't break.
Hierarchy of Java Exception classes
- Checked Exception
- Unchecked Exception
Check Exceptions: All exceptions other than Runtime Exceptions are known as Checked Exceptions as the compiler checks them during compilation to see whether the programmer has handled them or not. If these checked exceptions are not handled in the program, you will get a compilation error. For example, IOException, SQLException, ClassNotFoundException.
Unchecked Exceptions: Runtime Exceptions are known as Unchecked Exceptions. These exceptions are not checked at compile time so the compiler does not check whether the programmer has handled them or not but it is the responsibility of the programmer to handle the unchecked exceptions and provide a safe exit. For example, ArithematicExcpetion, ArrayIndexOutOfBoundsException, NullPointerException etc.
Try Catch in Java – Exception handling
Try Catch block contains set of statements where an exception may occur. A try block is always followed by a catch block, which handles the exception that occurs in associated try block. A try block must followed by catch blocks or finally block or both.
A catch block is where you handle the exceptions, the block must follow the try block. A single try block can have several catch blocks associated with it. You can catch different exceptions in different catch blocks. When an exception occurs in try block, the corresponding catch block that handles the particular exception executes. For example if an arithematic exception occurs in try block then the statements enclosed in catch block for arithematic exception executes.
try
{
//statements that may cause an exception
}
catch (exception(type) e(object))
{
//error handling code
}