The natural flow of a Java program is interrupted by an unexpected event is known as an Exception. When a method encounters an abnormal condition (an exception condition) that it can't handle itself, it may throw an exception. We can split up the exception into three main categories which are
For example consider the following lines of code.
Here it generate a compile time exception on the line which the BufferedReader created. The exception looks like follows
To fix the above program, we either need to specify list of exceptions using throws, or we need to use try-catch block. We have used throws in the below program. Since FileNotFoundException is a subclass of IOException, we can just specify IOException in the throws list and make the above program compiler-error-free.
Here follows some examples of checked exception
- Compile Time Exceptions
- Run Time Exceptions
- Errors
Compile Time Exception or Checked Exception
This exceptions are checked at compile time. If some code within a method throws a checked exception, then the method must either handle the exception or it must specify the exception using throws keyword.For example consider the following lines of code.
Here it generate a compile time exception on the line which the BufferedReader created. The exception looks like follows
To fix the above program, we either need to specify list of exceptions using throws, or we need to use try-catch block. We have used throws in the below program. Since FileNotFoundException is a subclass of IOException, we can just specify IOException in the throws list and make the above program compiler-error-free.
Here follows some examples of checked exception
- IOException
- SQLException
- DataAccessException
- ClassNotFoundException
- InvocationTargetException
Runtime Exception or Unchecked Exception
They are not checked at compile time. In C++, all exceptions are unchecked, so it is not forced by the compiler to either handle or specify the exception. It is up to the programmers to be civilized, and specify or catch the exceptions.. In Java, Unchecked Exception is direct sub Class of RuntimeException. What is major benefit of Unchecked Exception is that it doesn't reduce code readability and keeps the client code clean.Error
An Error “indicates serious problems that a reasonable application should not try to catch.”
Both Errors and Exceptions are the subclasses of java.lang.Throwable class. Errors are the conditions which cannot get recovered by any handling techniques. It surely cause termination of the program abnormally. Errors belong to unchecked type and mostly occur at runtime. Some of the examples of errors are Out of memory error or a System crash error.
Here follows the exception tree
No comments:
Post a Comment