Site icon TechVidvan

Java Throws Keyword with Examples

java throws keyword

In Java, the throws keyword indicates that a method might throw one or more exceptions during its execution. It’s an important part of exception handling and is particularly relevant for checked exceptions, which are exceptions that the compiler forces you to handle or declare in your code.

Using the throws keyword, you declare the potential exceptions that a method may propagate to its caller, allowing the caller to handle them appropriately.

Syntax:

return_type method_name() throws exception_class_name {  
}

Difference between throw and throws in Java

SI.No            Throw                 Throws
  

    1.

Used to trigger an exception in a method

 

 Used to describe the exception categories that a method can throw.
  

    2.

No more than one exception may be raised There could be a few exceptions declared.
    

     3.

Syntax:

An object (new type) used inside the method comes after the throw.

 

Syntax:

A class is immediately after throws and when the method signature is used.

Which exception should be declared:

Checked Exception only because:

Advantage:

Checked and Unchecked Exception:

Checked Exception:

They are checked at compile-time. For example, IOException, InterruptedException, etc..,

Unchecked Exception:

They are not checked at compile-time but at run-time. For example ArithmeticException, NullPointerException, ArrayIndexOfBoundException, exception under Error class, etc..,

1. Java throws an Example Program:

import java.io.*;
class Main {
  public static void findFile() throws IOException {
    File newFile=new File("test.txt");
    FileInputStream stream=new FileInputStream(newFile);
  }
  public static void main(String[] args) {
    try{
      findFile();
    } catch(IOException e){
      System.out.println(e);
    }
  }
}

Output:

java.io.FileNotFoundException: test.txt (No such file or directory)

Explanation:

Example 2: Java throw keyword

class Main {
  public static void divideByZero() {
    throw new ArithmeticException("Trying to divide by 0");
  }
  public static void main(String[] args) {
    divideByZero();
  }
}

Output:

Exception in thread “main” java.lang.ArithmeticException: Trying to divide by 0 at Main.divideByZero(Main.java:3)

at Main.main(Main.java:7)

Explanation:

Example 3: Throwing a Checked exception

import java.io.*;
class Main {
  public static void findFile() throws IOException {
    throw new IOException("File not found");
  }


  public static void main(String[] args) {
    try {
      findFile();
      System.out.println("Rest of code in try block");
    } catch (IOException e) {
      System.out.println(e.getMessage());
    }
  }
}

Output:

File not found

Explanation:

There are two cases specified in Java throws keyword:

Case 1: We have caught the exception, i.e. we have handled the exception using try/catch block.

Case 2: We have declared the exception, i.e. specified throws keyword with the method.

Case 1: Handle Exception Using try-catch block

In case we handle the exception, the code will be executed fine whether the exception occurs during the program or not.

import java.io.*;  
class M{  
 void method()throws IOException{  
  throw new IOException("device error");  
 }  
}  
public class Testthrows2{  
   public static void main(String args[]){  
    try{  
     M m=new M();  
     m.method();  
    }catch(Exception e){System.out.println("exception handled");}     
  
    System.out.println("normal flow...");  
  }  
}

Output:

exception handled

normal flow. . .

Explanation:

Case 2: Declare Exception

A. If an exception does not occur

import java.io.*;  
class M{  
 void method()throws IOException{  
  System.out.println("device operation performed");  
 }  
}  
class Testthrows3{  
   public static void main(String args[])throws IOException{//declare exception  
     M m=new M();  
     m.method();  
  
    System.out.println("normal flow...");  
  }  
}

Output:

device operation performed

normal flow…

Explanation:

B. If Exception occurs:

import java.io.*;  
class M{  
 void method()throws IOException{  
  throw new IOException("device error");  
 }  
}  
class Testthrows4{  
   public static void main(String args[])throws IOException{//declare exception  
     M m=new M();  
     m.method();  
  
    System.out.println("normal flow...");  
  }  
}

Output:

Exception in thread “main” java.io.IOException: device error at M.method(Testthrows4.java:4)

at Testthrows4.main(Testthrows4.java:10)

Explanation:

Summary

The throws keyword aids in creating a clear understanding between methods and the callers of those methods on any potential exceptions that can arise. This makes Java programs’ handling of exceptions more streamlined, readable, and reliable.

Exit mobile version