Checked vs Unchecked Exceptions in Java && throw and throws in Java

Checked vs Unchecked Exceptions in Java

In Java, there two types of exceptions:
1) Checked: 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 throws keyword.
For example, consider the following Java program that opens file at locatiobn “C:\test\a.txt” and prints 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
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();
    }
}
Output:
Exception in thread "main" java.lang.RuntimeException: Uncompilable source code - 
unreported exception java.io.FileNotFoundException; must be caught or declared to be 
thrown
 at Main.main(Main.java:5)
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.


import java.io.*;
 
class Main {
    public static void main(String[] args) throws IOException {
        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();
    }
}
Output: First three lines of file “C:\test\a.txt”
2) Unchecked are the exceptions that are not checked at compiled 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.
                   +-----------+
     | Throwable |
                   +-----------+
                    /         \
     /           \
          +-------+          +-----------+
          | Error |          | Exception |
          +-------+          +-----------+
    /  |  \           / |        \
         \________/   \______/      \
                   +------------------+
 unchecked  checked | RuntimeException |
     +------------------+
       /   |    |      \
      \_________________/
        
        unchecked
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.
class Main {
   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
Should we make our exceptions checked or unchecked?
Following is the bottom line from Java documents
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

 

throw and throws in Java

throw
The throw keyword in Java is used to explicitly throw an exception from a method or any block of code. We can throw either checked or unchecked exception. The throw keyword is mainly used to throw custom exceptions.
Syntax:
throw Instance
Example:
throw new ArithmeticException("/ by zero");
But this exception i.e, Instance must be of type Throwable or a subclass of Throwable. For example Exception is a sub-class of Throwable and user defined exceptions typically extend Exception class. Unlike C++, data types such as int, char, floats or non-throwable classes cannot be used as exceptions.
The flow of execution of the program stops immediately after the throw statement is executed and the nearest enclosing try block is checked to see if it has a catch statement that matches the type of exception. If it finds a match, controlled is transferred to that statement otherwise next enclosingtry block is checked and so on. If no matching catch is found then the default exception handler will halt the program.
// Java program that demonstrates the use of throw
class ThrowExcep
{
    static void fun()
    {
        try
        {
            throw new NullPointerException("demo");
        }
        catch(NullPointerException e)
        {
            System.out.println("Caught inside fun().");
            throw e; // rethrowing the exception
        }
    }
 
    public static void main(String args[])
    {
        try
        {
            fun();
        }
        catch(NullPointerException e)
        {
            System.out.println("Caught in main.");
        }
    }
}
Output:
Caught inside fun().
Caught in main.
Another Example:
// Java program that demonstrates the use of throw
class Test
{
    public static void main(String[] args)
    {
        System.out.println(1/0);
    }
}
Output:
Exception in thread "main" java.lang.ArithmeticException: / by zero
throws
throws is a keyword in Java which is used in the signature of method to indicate that this method might throw one of the listed type exceptions. The caller to these methods has to handle the exception using a try-catch block.
Syntax:
type method_name(parameters) throws exception_list
exception_list is a comma separated list of all the 
exceptions which a method might throw.
In a program, if there is a chance of rising an exception then compile always warn us about it and compulsorily we should handle that checked exception, Otherwise we will get compile time error saying unreported exception XXX must be caught or declared to be thrown. To prevent this compile time error we can handle the exception in two ways:
  1. By using try catch
  2. By using throws keyword
We can use throws keyword to delegate the responsibility of exception handling to the caller (It may be a method or JVM) then caller method is responsible to handle that exception.
// Java program to illustrate error in case
// of unhandled exception
class tst
{
    public static void main(String[] args)
    {
        Thread.sleep(10000);
        System.out.println("Hello Geeks");
    }
}
Output:
error: unreported exception InterruptedException; must be caught or declared to be thrown
Explanation : In the above program, we are getting compile time error because there is a chance of exception if the main thread is going to sleep, other threads get the chance to execute main() method which will cause InterruptedException.
// Java program to illustrate throws
class tst
{
    public static void main(String[] args)throws InterruptedException
    {
        Thread.sleep(10000);
        System.out.println("Hello Geeks");
    }
}
Output:
Hello Geeks
Explanation : In the above program, by using throws keyword we handled the InterruptedException and we will get the output as Hello Geeks
Another Example:
// Java program to demonstrate working of throws
class ThrowsExecp
{
    static void fun() throws IllegalAccessException
    {
        System.out.println("Inside fun(). ");
        throw new IllegalAccessException("demo");
    }
    public static void main(String args[])
    {
        try
        {
            fun();
        }
        catch(IllegalAccessException e)
        {
            System.out.println("caught in main.");
        }
    }
}
Output:
Inside fun().
caught in main.
Important points to remember about throws keyword:
  • throws keyword is required only for checked exception and usage of throws keyword for unchecked exception is meaningless.
  • throws keyword is required only to convince compiler and usage of throws keyword does not prevent abnormal termination of program.
  • By the help of throws keyword we can provide information to the caller of the method about the exception.

No comments:

Post a Comment