throws keyword in JAVA

Throws in JAVA

  • In JAVA the throws keyword is used to declare an exception.
  • Throws keyword does not handle an exception rather it just informs the programmer that an exception may occur.
  • Throws keyword is used only for checked exceptions as using it for unchecked exceptions will have no impact.
  • Throws keywords is used only for  constructors and methods but not for classes.
  • If a method is capable of causing an exception that it does not handle, it must specify this behavior so that callers of the method can guard themselves against that exception

Why do use throws keyword in Exception Handling in JAVA?

  • We use throws keyword so as to handover the task of handling checked exceptions to JVM as JVM by default does not handle checked exceptions
  • It is basically to tell JVM that handle the checked exceptions as JVM by default only handles unchecked exceptions.

Program(Save as Throws.java)

import java.io.*;
public class Throws
{
    public static void main(String args[]) throws FileNotFoundException
    {
        Throws obj = new Throws();
        obj.fileRead(); //comment this line when using try-catch
     
//Uncomment below lines to handle the exception using try-catch
       /*try
         {
             obj.fileRead();
         }    
         catch(FileNotFoundException e)
         {     
             System.out.println(e.toString()+ "\nException handled using try-catch!!!");
         }
    }

    public void fileRead() throws FileNotFoundException
    {
        File file = new File("C:\\File.txt");
        FileReader fr = new FileReader(file); 
    } 
}

Output

$javac Throws.java
$java Throws
Exception in thread "main" java.io.FileNotFoundException: C:\File.txt (No such file or directory)
	at java.io.FileInputStream.open0(Native Method)
	at java.io.FileInputStream.open(FileInputStream.java:195)
	at java.io.FileInputStream.<init>(FileInputStream.java:138)
	at java.io.FileReader.<init>(FileReader.java:72)
	at Throws.fileRead(Throws.java:24)
	at Throws.main(Throws.java:7)

From the output, we can see that the checked exception is handled by JVM at runtime, if we want to print our own message we can use try catch for handling the exception(we can comment throws next to main method while using try-catch).

If we do not use the throws keyword in main() method we will get a compile time error as we are calling fileRead() method which can throw a checked exception and JVM does not handle checked exceptions by default.

Share Me!