Difference Between Checked and Unchecked Exceptions in Java
Get Job-ready: Java Course with 45+ Real-time Projects! - Learn Java
Exceptions in Java is a vast concept. However, if you do not have a proper concept of how to handle exceptions, you are going to have a hard time debugging your code because the java compiler does not like uncaught exceptions.
What are these?
Why do we need checked and unchecked exceptions? Wouldn’t the world be a better place if there were no exceptions at all?
Let us see what we mean by checked and unchecked exceptions in Java.
What are Checked Exceptions in Java?
The JVM checks these exceptions during compile time. This is a very important point to understand.
If you do not explicitly mention the exceptions or provide appropriate actions to execute when the exception occurs, the compiler throws an error.
These come under compile-time errors.
If you do not have prior knowledge about these, you may spend the entire day looking at your code and still not come up with a possible explanation. I am telling you this from my experience. I have had some pretty rough days.
So simply speaking, you have to tell the compiler that a particular code will throw some exceptions, even if you are extremely sure that it won’t.
In order to deal with checked exceptions, you either have to mention what exception it can throw by using the “throws” keyword or you need to bind it with a try-catch block.
Let us take a simple example of a file operation in Java. However, if you are new to file operations be sure to check that article out first.
Program to illustrate Checked Exceptions in Java:
package com.dataflair.checkedunchecked; import java.io.*; public class Checked { public static void main(String[] args) { FileInputStream f = new FileInputStream("./test.txt");//This results in an error. f.close(); } }
Output:
FileInputStream f = new FileInputStream(“./test.txt”);//This results in an error.
^
Checked.java:9: error: unreported exception IOException; must be caught or declared to be thrown
f.close();
As you can see the compiler throws errors because I did not mention the exceptions possible in a throws clause or in a try-catch block.
So let us do it and see if there are still errors in it.
I added a throws IOException after the main method. We will see.
package com.dataflair.checkedunchecked; import java.io.*; public class Checked { public static void main(String[] args) throws IOException { FileInputStream f = new FileInputStream("./test.txt"); System.out.println("Shraman knows how to use Checked Exceptions."); System.out.println("He also created a file called test.txt in this directory"); f.close(); } }
Output:
He also created a file called test.txt in this directory
However, you might be confused as to why we are only mentioning the IOException class after the throws keyword.
This is because IOException is a superclass of the FileNotFound Exception.
So the compiler understands any exceptions which are a subclass are automatically taken care of.
We can also use try-catch blocks instead of the throws keyword. That is another method of handling checked exceptions.
Let us see.
Program to illustrate handling checked exceptions with try-catch blocks in Java:
package com.dataflair.checkedunchecked; import java.io.*; public class Checked { public static void main(String[] args) { try { FileInputStream f = new FileInputStream("./test.txt"); System.out.println("Shraman knows how to use Checked Exceptions."); System.out.println("He also created a file called test.txt in this directory"); f.close(); } catch (Exception e) { //TODO: handle exception System.out.println("There has been some sort of a problem! "); } } }
Output:
He also created a file called test.txt in this directory
As you can see in the program above, I did not mention the exceptions in the throws clause. I used a try-catch block instead.
This is another way to work with checked exceptions in Java.
What are Unchecked Exceptions in Java?
The compiler, unlike in Checked Exceptions, does not check for unchecked exceptions in the program.
It does not throw errors if you do not mention the exception using the throws keyword. It does not even give you compilation errors if you do not bind the code with a try-catch block.
These exceptions generally rise due to the poor input and data handling of a program.
One very popular exception is the ArithmeticException which arises if you divide a number by 0.
Let us see what it actually is with an example
Java program to illustrate the use of Unchecked Exceptions in Java:
package com.dataflair.checkedunchecked; import java.util.Scanner; public class Unchecked { public static void main(String[] args) { System.out.println("Let us learn about unchecked exceptions in Java"); int a,b; Scanner sc =new Scanner(System.in); System.out.println("Please enter the first number"); a=sc.nextInt(); System.out.println("Please enter the second number"); b=sc.nextInt(); int c=a/b; System.out.println("The quotient is "+c); } }
Output:
Please enter the first number
14
Please enter the second number
0
Exception in thread “main” java.lang.ArithmeticException: / by zero
at Unchecked.main(Unchecked.java:13)
If you observe in the above example, we did not explicitly use the throws keyword or a try-catch block, but the program still compiles like a charm.
However, when we ask the program to divide 15 with 0 it goes haywire. You can’t complain, because you are dividing the number by 0. What did you expect?
These are unchecked exceptions in Java.
However, we as developers must also check these exceptions even when these are not possible for the compile to check,
These error messages may cause the application to crash instead of notifying the user that their input is wrong.
So we should use try-catch blocks to properly handle the exception and provide appropriate output to the user.
We can change the above program to:
package com.dataflair.checkedunchecked; import java.util.Scanner; public class Unchecked { public static void main(String[] args) { try { System.out.println("Let us learn about unchecked exceptions in Java"); int a,b; Scanner sc =new Scanner(System.in); System.out.println("Please enter the first number"); a=sc.nextInt(); System.out.println("Please enter the second number"); b=sc.nextInt(); int c=a/b; System.out.println("The quotient is "+c); } catch (Exception e) { //TODO: handle exception System.out.println("Java faced \'"+ e.getMessage()+" \' exception."); System.out.println("Java thinks you entered a wrong input there. Please check and re-run the program."); } } }
Output:
Please enter the first number
13
Please enter the second number
0
Java faced ‘/ by zero ‘ exception.
Java thinks you entered a wrong input there. Please check and re-run the program.
Summary
At last, we are at the end of our article, checked and unchecked exceptions in Java.
We learned about what checked exceptions are, and the way we must use them in the program.
We also learned about unchecked exceptions and how they are necessary to be properly handled by the program to facilitate smooth execution.
Your opinion matters
Please write your valuable feedback about DataFlair on Google