Why you will know more differ about Checked Exception and Runtime Exception
The term exception refers to special events that can disrupt the flow of a normal program. Named after “exceptional events”, the word exception is a contraction of “exceptional”. The process of throwing an exception involves creating an object called an exception and passing it to the runtime.
The runtime system will then try to locate a method that can handle the exception by traversing the stack in reverse order. If it locates a method that has an exception handler, the runtime system will be successful. A block of code is an exception handler.
It can handle the exception. The runtime system will send the object of the exception to the appropriate handler if it finds one. This process is known as catching an exception. If the exception is not handled properly, then the program will end. In Java, all exceptions are inherited from the Throwable type. The compiler enforces the handling of checked exceptions. Runtime exceptions refer to exceptions that are not verified by the compiler.
For every exception in Java, an object is created that contains all of the information about the exception. Next, the program looks for its exception handler. The exception will be handled, resolved or the execution of the program stops if it is not found.
Java throws out two different types of exceptions. There are two types of exceptions.
- Checked exception
- Unchecked exception
What is a checked exception?
Checked Exceptions are either objects of the class java.lang.exception or its subclasses (except the java.lang.RuntimeException and its subclasses). The “checking” of checked exceptions occurs at compilation time. This means that the program must catch these exceptions, or toss them out of the window. Otherwise the compiler will complain and cause a compilation error. Many checked exceptions have become very familiar to programmers because of this. The IOException, its subclasses and their descendants are all checked exceptions. When a programmer accesses or modifies a file the compiler will check to ensure that the programmer has taken care of any IOExceptions.
Compile-time errors are exceptions that are verified by the Java compiler
The Java compiler requires that we handle exceptions somehow in our application code. These exceptions must be handled at an appropriate level within the application in order to notify the user of the failure and to ask them to try again or to come back later.
In general, exceptions marked as checked denote errors that are outside of the immediate control of the program. They are usually triggered when the software interacts with another system or network resource, e.g. database errors, network connection errors, missing files, etc.
All checked exceptions fall under the class
. As an example:
ClassNotFoundException
IOException
SQLException
Checked Exception Example
The FileNotFoundException
 is a checked exception in Java. Java will force us to deal with an error if the file is not present.
Try to read a file with handle FileNotFoundException
public static void main(String[] args)
{
FileReader file = new FileReader("somefile.txt");
}
In the above example, you will get a compile-time error with the message – Unhandled exception type FileNotFoundException
.
To make the program able to compile, we must handle this error situation in the try-catch block. Below given code will compile absolutely fine.
Read a file and apply exception handling
public static void main(String[] args)
{
try
{
FileReader file = new FileReader("somefile.txt");
}
catch (FileNotFoundException e)
{
//Alternate logic
e.printStackTrace();
}
}
What is a Runtime/Unchecked Exception?
The Runtime exceptions are Java. lang.RuntimeException and all its subclasses. They can theoretically be used for the same purposes as checked exceptions. However, the compiler does not force the correct handling. The Runtime exceptions are part of the unchecked family. Null Pointer Exception, Number Format Exception, Class Cast Exception, and Array Index Out Of Bounds Exception are common runtime exceptions in Java.
Unchecked exceptions are subclasses runtimeException
.
ArithmeticException
arrayStoreException
classCastException
RuntimeException
itself is a subclass to, i.e. All unchecked classes of exception should be checked implicitly but they aren’t.”
Unchecked Exception Example
When we run the example, it throws a code>NullPointerException/code>. But when we run the example, it throws NullPointerException
. NullPointerException in Java is an exception that cannot be checked.
NullPointerException is not checked by default in JVM
public static void main(String[] args)
{
try
{
FileReader file = new FileReader("pom.xml");
file = null;
file.read();
}
catch (IOException e)
{
//Alternate logic
e.printStackTrace();
}
}
What’s the difference between a Checked exception and a Runtime Exception
Both checked and runtime errors are undesirable events that occur during program execution. However, there is a difference between them. The compiler enforces the handling of checked exceptions, while runtime exceptions do not. Runtime exceptions are not subject to the same requirement. Runtime exceptions are therefore included in the category of unchecked errors and exceptions.
Checked exceptions have the disadvantage that even though the programmer does not understand how to do it, she still has to deal with it. If the programmer throws an exception and does not wrap the previous exception, then the stack trace of the first exception is lost. Runtime exceptions can be very useful in this situation. Programmers are able to write less code because all runtime errors can be dealt with in one place. The programmer is not surprised by checked exceptions, because they must be caught. The programmer will know exactly which exceptions can be caught by certain methods. Unknown to the programmer, a variety of runtime errors can occur.
comparison chart between Checked Exception and Runtime Exception
Checked exception | Unchecked Exception |
---|---|
There are checked exceptions at the time of compilation. | Runtime exceptions are unchecked. |
A checked exception is checked by the compiler. | These types of exceptions are not checked by the compiler. |
The compilation process can handle these types of exceptions. | This type of exception cannot be caught or handled at compilation time, as they are generated by mistakes within the program. |
The subclasses of exception classes are these. | These are runtime errors and are therefore not included in the class Exception. |
The JVM must catch the exception and then handle it. | The JVM doesn’t require an exception for catching and handling. |
Example of checked exceptions
|
Examples of unchecked exceptions
|
Checked and Runtime Exceptions in Java
Another burning question, apart from knowing the difference between checked and Runtime exceptions is whether you should make custom Exceptions unchecked or not by deriving them from Java. lang.RuntimeException or checked? This decision is entirely yours, though the Java community has some ideas. When in doubt, I tend to use JDK and follow its practices.
If a method has a high probability of failing and its chances are greater than 50%, it should be thrown a Checked Exception in order to provide alternate processing if it fails. A second thought would be to uncheck errors and derive them from RuntimeException, e.g. java. lang.NullPointerException.
The Checked Exception enforces the correct handling of error conditions, but it is theoretical and most programs just appease the compilers with a try/catch block rather than correctly handling errors in the catch blocks.
Checked exceptions are more prone to making your code look ugly because they add boilerplate code, such as a block of try-catch and finally. This issue has been addressed in part by JDK 7’s improved exception handling. It introduces automatic resource management blocks or ARM and allows multiple exceptions to be caught in the same block.
This is all about and the differences between checks in Java, runtime exceptions. This question could also be posed as unchecked vs checked exception. Unchecked indicates that the compiler does not check for handling exceptions, while Checked signifies the compiler performs a thorough review.
Exception Handling Best Practices
- When a method fails to perform as it should, checked exceptions are available. A method calledÂ
PrepareSystem()
, for example, pre-populates the configuration files before performing some configuration. It can declare throwing FileNotFoundException, which implies that the method uses configuration files from the file system and they are missing. - In such situations, it is ideal to use checked exceptions for flow control and resource errors.
- Only throw exceptions that the method cannot handle. It is important that the method tries to deal with it immediately after it has encountered it. Only throw the exception if the method cannot handle the problem.
- It is best to place exceptions near the name of the method when defining method signatures. If the method is named, then it is expected to throwÂ
FileNotFoundException
?. If the method is named, then it is expected to throwÂNoSuchProviderException
. - These types of exceptions are also important to check, as they force the caller of these methods to address the inherent problems of their semantics.
- When creating a custom exception the rule to follow is that if it’s reasonable for a client to expect a recovery from an error, we should make sure this exception is checked. Uncheck the box if a client can’t do anything about it.
The conclusion of the article is
The biggest distinction between unchecked and checked exceptions is that unchecked errors are created during the run-time. Checked Exceptions and Runtime Exceptions differ in their handling, compile-time checking, recoverability, inheritance, and impact on program flow. Knowing when to use each type of exception is an essential skill for writing robust and reliable Java code.