Code360 powered by Coding Ninjas X Naukri.com. Code360 powered by Coding Ninjas X Naukri.com
Table of contents
1.
Introduction
2.
Java Throws Keyword
2.1.
Syntax
3.
Example
3.1.
Code 1
3.2.
Code 2
3.3.
Code 3
4.
Throw VS Throws
5.
Frequently Asked Questions
6.
Key Takeaways
Last Updated: Mar 27, 2024

Throws keyword

Crack Google SDE interview : Essential projects
Speaker
Saurav Prateek
SDE-2 @
20 Jun, 2024 @ 01:30 PM

Introduction

Errors and Exceptions are the standard part of any application. It helps determine that something unsuitable has occurred, such as syntax or input errors. In Java, throws is the keyword declared with the method's name.

Also read, Duck Number in Java  and Swap Function in Java

Java Throws Keyword

The Java throws keyword is used to define an exception. It provides information to the programmer that the error has occurred. The programmer needs to give the exception handling code to maintain the normal code flow. It is mainly used to handle the checked exception. 

Syntax

return type method_name() throws exception class_name {
	//method name
}
Get the tech career you deserve, faster!
Connect with our expert counsellors to understand how to hack your way to success
User rating 4.7/5
1:1 doubt support
95% placement record
Akash Pal
Senior Software Engineer
326% Hike After Job Bootcamp
Himanshu Gusain
Programmer Analyst
32 LPA After Job Bootcamp
After Job
Bootcamp

Example

Code 1

public class Code1 {
    static void eligible(int age) throws ArithmeticException {
        if (age < 18) {
            throw new ArithmeticException("You can't vote - You should be at least 18 years old to cast your vote.");
            
        }
        else {
            System.out.println("You can vote - You are old enough to cast your vote!");
            
        }
    }
    public static void main(String[] args) {
        eligible(15); // Set age to 15 (which is below the eligible age...)
    }
} 

Output

Exception in thread "main" java.lang.ArithmeticException: You can't vote - You should be at least 18 years old to cast your vote.
at Code1.eligible(Code1.java:4)
at Code1.main(Code1.java:13)


Practice by yourself on java online compiler.

In this code, we check that the user is eligible for voting or note. We have made a function eligible, and we also throw an exception to check if the entered age is greater than 18(voting age). If the user is eligible to vote, the code will not throw an exception. Otherwise, it will throw an exception.

Code 2

import java.io.IOException;  


public class Ex6{
    void m()throws IOException{
        throw new IOException("device error");//checked exception  
    }  
    
    void n()throws IOException{
        m();
    }
    
    void p(){
        try{
            n();
            
        }
        catch(Exception e){
            System.out.println("exception handled");
        }
    }
    public static void main(String args[]){
        Ex6 obj=new Ex6();
        obj.p();
        System.out.println("normal flow...");
    }
}

 

Output

exception handled
normal flow…

 

In this code, we used an example of a try-catch exception, where we send some input to the try block. In the try block, we have called some function, and that called function throws an exception, and in that block, it contains some other functions which triggers the exception. We also created an object of the class to call the function. 

Code 3

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

Output

exception handled
normal flow…

 

In this code, we are throwing an exception. We first create an object of this class after that we will call that function. The function will check and catch the exception. If the exception is caught, it will execute the code block which is inside the exception.

Must Read Static Blocks In Java.

Throw VS Throws

Key Difference throw throws
Usage It can be used inside a function to throw an exception. It is used inside the function signature, which leads to exceptions.
Exceptions This is used to throw an exceptions explicitly. This can declare multiple exceptions.
Syntax This keyword is followed by an exception to be thrown. This is followed by class names that are to be thrown.
Declaration It is declared within a function. This is declared with the function signature.

 

Frequently Asked Questions

  1. What is the purpose of the throws keyword?
    The function of the throws keyword is to declare exceptions during the code execution. It is necessary to use the throws keyword to list the exception that can be thrown.
     
  2. Can throw be used without throws keyword?
    When an exception is thrown in a catch block, you can re-throw it using the throw keyword. If you re-throw the exception, this exception will now be generated in the method that calls the current one in the throws clause's case.

Key Takeaways

In this blog, we have covered about throws keyword. We have given a brief introduction about the throws keyword and what is Java throws keyword is, along with its syntax. We also took a few examples of how throws keywords might be used in different scenarios. If you want to learn more about throws keywords, visit our website, Exception Handling.

Previous article
Flow control in Try-Catch and Finally Blocks in Java
Next article
Try catch block
Live masterclass