Exception Handling is the mechanism to handle Runtime Exceptions. We need to handle such exceptions to prevent abrupt termination of the program. It helps us to maintain the normal flow of the application.
What is Exception?
An Exception can be anything which interrupts the normal flow of the program. When Exception occurs system generates an error message. We can manage this using exception handler.
Difference in Error & Exception
Both Error and Exception are derived from java.lang.Throwable in Java but the main difference between Error and Exception is kind of error they represent.
Errors are “serious issues and abnormal conditions that most applications should not try to handle”. Error defines problems that are not expected to be caught under normal circumstances by the program. For example memory error, hardware error, JVM error etc.
Selenium Testing Video Tutorial:
Exceptions are “conditions that a reasonable application might want to catch or conditions within the code”. A developer can handle such conditions and take necessary corrective actions.
Let’s see the hierarchy of Exception Handling in Java. Throwable is the parent class of all Exception.
Exception class is for exceptional conditions that program should catch. This class is extended to create user specific exception classes.
RuntimeException is a subclass of Exception. Exceptions under this class are automatically defined for programs.
Error are typically ignored in code because you can rarely do anything about an error. Example: if the stack overflow occurs, an error will arise. This type of error is not possible to handle in code.
Types of Exception
In Java, there are two types of Exception.
- Checked Exception – The exception that can be predicted by the programmer are called checked Exception or we can say 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 exceptions are not handled/declared in the program, it will give the compilation error.
like – ClassNotFoundException, IllegalAccessException, NoSuchFieldException, EOFException etc.
- UnChecked Exception – Unchecked exceptions are the class that extends RuntimeException. The unchecked exception is ignored at compile time. These exceptions need not be included in any method’s throws list because the compiler does not check to see if a method handles or throws these exceptions.
Like – ArithmeticException, ArrayIndexOutOfBoundsException, NullPointerException, NegativeArraySizeException etc.