Exception is an unwanted or unexpected event, which occurs during the execution of a program, i.e. at run time, that disrupts the normal flow of the program’s instructions. In Java, there are two types of exceptions:
- Checked exceptions
- Unchecked exceptions
Checked Exceptions
These are the exceptions that 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 the throws keyword. In checked exception, there are two types: fully checked and partially checked exceptions. A fully checked exception is a checked exception where all its child classes are also checked, like IOException, InterruptedException. A partially checked exception is a checked exception where some of its child classes are unchecked, like Exception.
For example, consider the following Java program that opens the file at location “C:testa.txt” and prints the first three lines of it. The program doesn’t compile, because the function main() uses FileReader() and FileReader() throws a checked exception FileNotFoundException. It also uses readLine() and close() methods, and these methods also throw checked exception IOException
Example:
Java
import
java.io.*;
class
GFG {
public
static
void
main(String[] args)
{
FileReader file =
new
FileReader(
"C:\test\a.txt"
);
BufferedReader fileInput =
new
BufferedReader(file);
for
(
int
counter =
0
; counter <
3
; counter++)
System.out.println(fileInput.readLine());
fileInput.close();
}
}
Output:
To fix the above program, we either need to specify a list of exceptions using throws, or we need to use a 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.
Example:
Java
import
java.io.*;
class
GFG {
public
static
void
main(String[] args)
throws
IOException
{
FileReader file =
new
FileReader(
"C:\test\a.txt"
);
BufferedReader fileInput =
new
BufferedReader(file);
for
(
int
counter =
0
; counter <
3
; counter++)
System.out.println(fileInput.readLine());
fileInput.close();
}
}
Output:
First three lines of file "C:testa.txt"
Unchecked Exceptions
These are the exceptions that 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, exceptions under Error and RuntimeException classes are unchecked exceptions, everything else under throwable is checked.
Consider the following Java program. It compiles fine, but it throws ArithmeticException when run. The compiler allows it to compile because ArithmeticException is an unchecked exception.
Example:
Java
class
GFG {
public
static
void
main(String args[])
{
int
x =
0
;
int
y =
10
;
int
z = y / x;
}
}
Output:
Exception in thread "main" java.lang.ArithmeticException: / by zero at Main.main(Main.java:5) Java Result: 1
In short unchecked exceptions are runtime exceptions that are not required to be caught or declared in a throws clause. These exceptions are usually caused by programming errors, such as attempting to access an index out of bounds in an array or attempting to divide by zero.
Unchecked exceptions include all subclasses of the RuntimeException class, as well as the Error class and its subclasses.
Here are some examples of unchecked exceptions in Java:
ArrayIndexOutOfBoundsException: This exception is thrown when you attempt to access an array index that is out of bounds.
NullPointerException: This exception is thrown when you attempt to access a null object reference.
ArithmeticException: This exception is thrown when you attempt to divide by zero or perform an invalid arithmetic operation.
Please write comments if you find anything incorrect, or if you want to share more information about the topic discussed above
In this Java exceptions tutorial, learn what an exception is in Java, and the difference between a checked exception and an unchecked exception. We will also learn some Java exception handling best practices.
1. What is Exception in Java?
“An exception is an unexpected event that occurred during the execution of a program, and disrupts the normal flow of instructions.”
- In Java, all errors and exceptions are of type with
Throwable
class. - When an error occurs within a method, the method creates an object (or any subtype of
Throwable
) and hands it off to the runtime system. This object is called the exception object. - The exception object contains information about the error, including the exception type and the program’s state when the error occurred.
- Creating an exception object and handing it to the runtime system is called throwing an exception.
A few examples of an exception in the program execution can be:
- The user enters alphanumeric input, and the program excepts numeric input.
- The program tries to read the file, but the file does not exist in the specified location.
- A network connection terminated while reading data from a webservice.
try {
Integer.parseInt("six") ; //This line throws an exception
}
catch(NumberFormatException nfe) {
//handle exception
}
2. Handling a Thrown Exception
We have two choices when an exception object is created in our application;
- Either we will handle it within the method using the try-catch block.
- Or we can pass it to the caller method to let it handle.
This is a very important decision to be made while setting the responsibilities of a method.
A method should clearly indicate what exceptions it will handle and which it will not. It is defined in the method declaration using the throws
keyword.
To handle the exception, We must catch the exception in catch section of try-catch block.
try {
//code
}
catch(Exception e) {
//handle exception
}
If an exception is not handled in the application, then it will propagate to the JVM. The JVM usually terminates the program.
3. Checked Exception vs Unchecked Exception
In Java, exceptions are broadly categorized into two sections:
- Checked exceptions
- Unchecked exceptions
3.1. Checked Exceptions
The checked exceptions are those exceptions, as the name suggests, which a method must handle in its body or throw to the caller method so the caller method can handle it.
Checked exceptions are checked by the Java compiler, so they are called compile-time exceptions.
Java compiler forces us to handle these exceptions in some manner in the application code. We must handle these exceptions at a suitable level inside the application to inform the user about the failure and ask him to retry or come later.
Generally, checked exceptions denote error scenarios outside the program’s immediate control. These usually occur when the program interacts with other systems/network resources e.g. database errors, network connection errors, missing files, etc.
Note that all checked exceptions are subclasses of Exception
class. For example,
ClassNotFoundException
IOException
SQLException
Checked Exception Example
The FileNotFoundException
is a checked exception in Java. Anytime, we want to read a file from the filesystem, Java forces us to handle an error situation where the file may not be present in the place.
public static void main(String[] args)
{
FileReader file = new FileReader("somefile.txt");
}
In the above example, you will get 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.
public static void main(String[] args)
{
try
{
FileReader file = new FileReader("somefile.txt");
}
catch (FileNotFoundException e)
{
//Alternate logic
e.printStackTrace();
}
}
3.2. Unchecked Exception
Unchecked exceptions are not checked by the compiler. These are called runtime exceptions. Unchecked exceptions will come into life and occur in the program, once any buggy code is executed.
In Java, the compiler does not force a member method to declare the unchecked exceptions into the method declaration. Generally, such methods almost always do not declare them.
Unchecked Exceptions are subclasses of RuntimeException
class.
ArithmeticException
ArrayStoreException
ClassCastException
The strange thing is that RuntimeException
is itself subclass of Exception
i.e. all unchecked exception classes should have been checked exceptions implicitly, BUT they are not.”
Unchecked Exception Example
The code in the given program does not give any compile-time error. But when we run the example, it throws NullPointerException
. NullPointerException is an unchecked exception in Java.
public static void main(String[] args)
{
try
{
FileReader file = new FileReader("pom.xml");
file = null;
file.read();
}
catch (IOException e)
{
//Alternate logic
e.printStackTrace();
}
}
4. Exception Handling Best Practices
- Checked exceptions can be used when a method may fail to do what it must. For example, a method named
prepareSystem()
that pre-populates configuration files and does some configuration using them. It can declare throwing FileNotFoundException, which implies that the method uses configuration files from the file system and they are missing. - Ideally, checked exceptions should never be used for programming errors but should absolutely be used for resource errors and flow control in such cases.
- Throw only those exceptions that a method can not handle by any means. The method should first try to handle it as soon as it encounters it. Throw the exception only if it is impossible to handle it inside the method.
- A good way to define method signatures is to declare exceptions close to method name. If the method is named
openFile()
, then it is expected to throwFileNotFoundException
?. If the method is namedfindProvider()
, then it is expected to throwNoSuchProviderException
. - Also, these types of exceptions should be checked as it forces the caller to deal with the problems inherent to the semantics of the methods.
- If we are creating any custom exception, then the rule is if a client can reasonably be expected to recover from an exception, make it a checked exception. If a client cannot do anything to recover from the exception, make it an unchecked exception.
5. Conclusion
In this Java tutorial, we learned about Java exceptions. We learned the difference between checked vs unchecked exceptions in Java and how to handle unchecked exceptions and exception hierarchy in Java with examples.
Remember, the biggest difference between checked and unchecked exceptions is that checked exceptions are forced by the compiler and used to indicate exceptional conditions that are out of the program’s control, while unchecked exceptions occur during runtime and are used to indicate programming errors.
Happy Learning !!
Checked and Unchecked Exceptions in Java | In the previous tutorial, we have familiarized that there are two types of exceptions in java: First is predefined exceptions, and second user-defined exceptions.
The predefined exceptions are those exceptions that are already defined by the java system.
All the predefined exceptions are further divided into two groups:
- Checked Exceptions
- Unchecked Exceptions
Checked exceptions are those exceptions that are checked by the java compiler itself at compilation time and are not under runtime exception class hierarchy.
If a method throws a checked exception in a program, the method must either handle the exception or pass it to a caller method.
We must handle checked exceptions either by using try and catch block or by using a throws clause in the method declaration. If not handles properly, it will give a compile-time error.
Most people have confusion and say that checked exceptions occur at compile-time, that is wrong. All exceptions always occur at runtime only, but some exceptions are detected at compile-time and some other at runtime.
The exceptions that are checked by Java compiler at compilation time is called checked exception in Java. All the exceptions except RuntimeException, Error, and their subclasses are checked exceptions.
Note: Compile-time errors are not exceptions. They come under errors. In Java, only runtime errors come under exceptions.
List of Checked Exceptions in Java
A list of some important checked exceptions is given below:
- ClassNotFoundException
- InterruptedException
- InstantiationException
- IOException
- SQLException
- IllegalAccessException
- FileNotFoundException, etc
Let’s take an example program where we will pause the main thread for a specified amount of time and see what happens on the execution of the program.
Program code 1:
package exceptionHandling; public class CheckedExceptionEx1 { public static void main(String[] args) { System.out.println("Hello Java"); Thread.sleep(1000); // Here, main thread paused for a specified amount of time. // Compilation error. } }
Output: Exception in thread "main" java.lang.Error: Unresolved compilation problem: Unhandled exception type InterruptedException
Explanation:
In the above code, there is a compilation error: “Unhandled exception type InterruptedException”. This is because thread.sleep(); method throws an InterruptedException that has been not handled by a try-catch or throws clause.
Since InterruptedException is a checked exception that is checked by the compiler itself for the smooth execution of the program at runtime, therefore, we got a compilation error at compile-time and InterruptedException exception at runtime.
Handle Checked Exception in Java
To avoid this compilation error, we will have to handle this checked exception either using a try-catch block or throws clause. Let’s handle it and see what will be the output?
Program code 2:
public class CheckedExceptionEx1 { public static void main(String[] args) { System.out.println("Hello Java"); // Apply the try-catch block to handle checked exception. try { Thread.sleep(1000); } catch(InterruptedException e) { e.printStackTrace(); } } }
Output: Hello Java
As you can see in the above code, we have handled checked exceptions by using a try-catch block. You can also use throws clause instead of the try-catch block.
Let’s take an example program in which we will handle Java checked exceptions using a throws clause.
Program code 3:
package exceptionHandling; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; public class CheckedExceptionEx { public static void main(String[] args) throws FileNotFoundException { File file = new File("not_existing_file.txt"); FileInputStream stream = new FileInputStream(file); } }
Output: Exception in thread "main" java.io.FileNotFoundException: not_existing_file.txt (The system cannot find the file specified)
Explanation:
In the above code, there is no compilation error because we have handled checked exception by using throws clause. But, at runtime, FileNotFoundException exception occurs because we are trying to access a non-existing file.
Unchecked Exceptions (Runtime Exceptions) in Java
Unchecked exceptions in Java are those exceptions that are checked by JVM, not by java compiler. They occur during the runtime of a program.
All exceptions under the runtime exception class are called unchecked exceptions or runtime exceptions in Java.
We can write a Java program and compile it. But we cannot see the effect of unchecked exceptions and errors until we run the program.
This is because Java compiler allows us to write a Java program without handling unchecked exceptions and errors.
Java compiler does not check runtime exception at compile time whether programmer handles them or not.
If a runtime exception occurs in a method and the programmer does not handle it, JVM terminates the program without the execution of rest of the code.
List of Unchecked Exceptions in Java
Some important examples of runtime exceptions are given below:
- ArithmeticException
- ClassCastException
- NullPointerException
- ArrayIndexOutOfBoundsException
- NegativeArraySizeException
- ArrayStoreException
- IllegalThreadStateException
- SecurityException, etc.
Let’s take an example program based on Java runtime exception.
Program code 4:
public class UncheckedExceptionEx1 { public static void main(String[ ] args) { int x = 10; int y = 0; int z = x/y; // runtime exception. System.out.println(z); } }
Output: Exception in thread "main" java.lang.ArithmeticException: / by zero at exceptionHandling.UncheckedExceptionEx1.main(UncheckedExceptionEx1.java:9)
You will have noticed that the above code has become compile successfully but when you will go to execute it, so it would throw ArithmeticException. This shows that runtime exceptions do not occur during compilation.
Handle Runtime Exception in Java
To avoid this runtime error, we will have to handle this unchecked exception either using a try-catch block or throws clause. Let’s handle it and see what will be the output?
Program code 5:
public class HandleRuntimeException { public static void main(String[] args) { int x = 10; int y = 0; // Apply try-catch block to handle runtime exception. try { int z = x/y; // runtime exception. System.out.println(z); } catch(ArithmeticException ae) { System.out.println("A number cannot be divided by zero"); } } }
Output: A number cannot be divided by zero
In this example, we have handled runtime exceptions by using a try-catch block and generated user friendly message on the console. We can also use a throws clause instead of the try-catch block to handle runtime exception.
Let’s see one more example program based on unchecked exceptions.
Program code 6:
public class UncheckedExceptionEx2 { public static void main(String[] args) { int x[ ] = {1, 2, 3, 4}; /* Here, an array contains only 4 elements, but we will try to * display the value of 6th element. It should throw * ArrayIndexOutOfBoundsException */ System.out.println(x[6]); } }
Output: Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 6
Explanation:
The above code would also compile successfully, but at runtime, we will get ArrayIndexOutOfBoundsException unchecked exception. This exception is thrown when an array element is accessed out of the index.
We can handle exception found in the above code by using try-catch block carefully. Using try-catch block, we can generate a user-friendly message so that we will be able to correct this issue. Let’s handle it.
Program code 7:
public class UncheckedExceptionEx2 { public static void main(String[] args) { try { int x[ ] = {1, 2, 3, 4}; System.out.println(x[6]); } catch(ArrayIndexOutOfBoundsException e) { System.out.println("Specified index does not exist. " + "Please correct the error."); } } }
Output: Specified index does not exist. Please, correct the error.
Difference between Checked and Unchecked Exceptions in Java
There are many important differences between checked and unchecked exceptions in java. They are as follows:
1. The classes that directly inherit Throwable class except RuntimeException and Error are called checked exceptions whereas, classes that directly inherit RuntimeException are called unchecked exceptions.
2. Checked exceptions are checked and handled at compile-time whereas, unchecked exceptions are not checked and handled at compile time. They are checked at runtime.
3. Examples of checked exceptions are IOException, SQLException, ClassNotFoundException, etc whereas, examples of unchecked exceptions are ArithmeticException, ClassCastException, NullPointerException, IllegalArgumentException, etc.
4. When a checked exception occurs in a method, the method must either catch the exception or pass exception to its caller method. But in the case of an unchecked exception, Java compiler does not force to catch exception or to declare it in a throws clause.
5. Checked exceptions in java extends Exception class, whereas unchecked exceptions extends RuntimeException class.
6. A checked exception happens when there is a chance of a higher failure rate. whereas unchecked exceptions occur, mostly due to programming mistakes/errors.
Hope that this tutorial has covered all the basic points of checked and unchecked exceptions in java with example programs. I hope that you will have understood the list of checked and unchecked exceptions.
If you find anything incorrect in this tutorial, please inform us via email. Your email will be precious to us. In the next tutorial, we will learn try-catch block in Java with the help of examples.
Thanks for reading!!!
Next ⇒ Java Try Catch Block⇐ PrevNext ⇒