In: Computer Science
Exception Handling in Java
In addition to what we have learned from the course materials, there are other ways to categorize exceptions in Java such as checked and unchecked exceptions. Please conduct online research on these two categories, share what you find. Of these two kinds of exceptions (checked and unchecked), which method do you prefer? Which method is easier?
Checked Exception:-
Checked exceptions are checked at compile-time. It means if a method is throwing a checked exception then it should handle the exception using try-catch block or it should declare the exception using throws keyword, otherwise the program will give a compilation error...
Example:-
import java.io.*;
class Main {
public
static void main(String[] args)
{
FileReader
file = new
FileReader("C:\\test\\a.txt");
BufferedReader
fileInput = new
BufferedReader(file);
//
Print first 3 lines of file "C:\test\a.txt"
for
(int counter =
0; counter < 3;
counter++)
System.out.println(fileInput.readLine());
fileInput.close();
}
}
Unchecked Exception:-
Unchecked exceptions are not checked at compile time. It means if your program is throwing an unchecked exception and even if you didn’t handle/declare that exception, the program won’t give a compilation error. Most of the times these exception occurs due to the bad data provided by user during the user-program interaction. It is up to the programmer to judge the conditions in advance, that can cause such exceptions and handle them appropriately. All Unchecked exceptions are direct sub classes of RuntimeException class..
class Example {
public static void main(String args[])
{
int num1=10;
int num2=0;
/*Since I'm dividing an integer with 0
* it should throw ArithmeticException
*/
int res=num1/num2;
System.out.println(res);
}
}
I would prefer unchecked exception because Checked Exceptions are used for predictable, but unpreventable errors that are reasonable to recover from whereas Unchecked Exceptions are used for everything else.
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..