The throw keyword is used to throw an exception in Java. In this guide, you will learn what is a throw keyword and how to use it in a java program. This article covers various examples to demonstrate the use of throw keyword.
What is a throw keyword?
In the exception handling guide, we learned how java program throws an exception when there is bad input data, such exceptions are automatically raised. However, we can also throw exception explicitly using throw keyword. It is like, you have written a condition and when that condition occurs, you would want an error message to be shown to user, you can do this by throwing an exception on that particular condition.
For example: You have written a program where you are showing grades of the student based on the input total marks. The total marks is out of 100, let’s say a user enters the total marks as 200, this will not cause any exception to be thrown automatically. However you can set a condition in the program to throw an exception when user enters total marks more than 100. Let’s write a java program for this example:
import java.util.Scanner; public class JavaExample { //function to check if person is eligible to vote or not public static void printGrades(int marks) { if(marks>100) { //since total marks cannot exceed 100, we are throwing an exception //to show user that he has done a mistake while entering data throw new ArithmeticException("Total Marks cannot be more than 100"); } else if(marks>=60){ System.out.println("Grade A"); } else if(marks>33 && marks<60){ System.out.println("Grade B"); } else{ System.out.println("Grade C"); } } //main method public static void main(String args[]){ //asking the user to enter total marks System.out.print("Enter total marks: "); Scanner scan = new Scanner(System.in); int totalMarks = scan.nextInt(); //calling the method to print grades printGrades(totalMarks); } }
Output 1: When user enters the total marks more than 100
Output 2: When user enters valid total marks
How to throw your own exception explicitly using throw keyword
In the above example, we have thrown a predefined exception. However you can also throw a custom exception using throw keyword. Refer this guide to understand how to create your own exceptions.
class MyOwnException extends Exception { public MyOwnException(String msg){ super(msg); } } class EmployeeTest { static void employeeAge(int age) throws MyOwnException{ if(age < 0) throw new MyOwnException("Age can't be less than zero"); else System.out.println("Input is valid!!"); } public static void main(String[] args) { try { employeeAge(-2); } catch (MyOwnException e) { e.printStackTrace(); } } }
Output:
beginnersbook.com.MyOwnException: Age can't be less than zero
Note: Method call should be in try block as it is throwing an exception.
How to throw unchecked exceptions using throw keyword
In the student grades example, we have thrown unchecked exceptions, however we can also throw checked exception using throw keyword. Refer this guide to learn more about checked and unchecked exceptions.
import java.io.*; public class JavaExample { //method to read a file public static void readMyFile() throws FileNotFoundException { FileReader file = new FileReader("C:\\Users\\Chaitanya\\myfile.txt"); BufferedReader text = new BufferedReader(file); System.out.println(text); //if file doesn't exist throw a checked exception if(text == null) { throw new FileNotFoundException(); } } public static void main(String args[]){ try { readMyFile(); } catch (FileNotFoundException e) { System.out.println("File Not Found: "+e); } } }
Output:
File Not Found: java.io.FileNotFoundException: C:\Users\Chaitanya\myfile.txt (No such file or directory)
Similarly other checked exceptions, such as ClassNotFoundException
, IOException
etc. can be thrown.
In this article, we have learned how to throw a checked and unchecked exception using throw keyword. We also learned how to throw a user-defined exception.
Recommended Posts:
- Try-catch block in Java
- User defined Exception in Java
- Difference between throw and throws in Java
- Throws in Java with example
Previous Article: Exception handling in Java
Next Article: Throws keyword in Java
Anwesa says
Please show how to catch the thrown exception
Varma says
what is the need of throwing an Exception Explicitly…?