BeginnersBook

  • Home
  • Java
    • Java OOPs
    • Java Collections
    • Java Examples
  • C
    • C Examples
  • C++
    • C++ Examples
  • DBMS
  • Computer Network
  • Python
    • Python Examples
  • More…
    • jQuery
    • Kotlin
    • WordPress
    • SEO
    • JSON
    • JSP
    • JSTL
    • Servlet
    • MongoDB
    • XML
    • Perl

Throw Keyword in Java with Examples

Last Updated: September 12, 2022 by Chaitanya Singh | Filed Under: java

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
throw keyword example
Output 2: When user enters valid total marks
throw keyword exception not thrown

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

Top Related Articles:

  1. Java Exception Handling Examples
  2. Constructor Overloading in Java with examples
  3. Checked and unchecked exceptions in java with examples
  4. Java Throws Keyword in Exception handling
  5. TreeMap in Java with Example

Tags: Exception-Handling

About the Author

I have 15 years of experience in the IT industry, working with renowned multinational corporations. Additionally, I have dedicated over a decade to teaching, allowing me to refine my skills in delivering information in a simple and easily understandable manner.

– Chaitanya

Comments

  1. Anwesa says

    March 9, 2016 at 1:58 PM

    Please show how to catch the thrown exception

    Reply
  2. Varma says

    September 2, 2017 at 2:46 PM

    what is the need of throwing an Exception Explicitly…?

    Reply

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

Java Tutorial

Java Introduction

  • Java Index
  • Java Introduction
  • History of Java
  • Features of Java
  • C++ vs Java
  • JDK vs JRE vs JVM
  • JVM - Java Virtual Machine
  • First Java Program
  • Variables
  • Data Types
  • Operators

Java Flow Control

  • Java If-else
  • Java Switch-Case
  • Java For loop
  • Java while loop
  • Java do-while loop
  • Continue statement
  • break statement

Java Arrays

  • Java Arrays

OOPs Concepts

  • OOPs Concepts
  • Constructor
  • Java String
  • Static keyword
  • Inheritance
  • Types of inheritance
  • Aggregation
  • Association
  • Super Keyword
  • Method overloading
  • Method overriding
  • Overloading vs Overriding
  • Polymorphism
  • Types of polymorphism
  • Static and dynamic binding
  • Abstract class and methods
  • Interface
  • Abstract class vs interface
  • Encapsulation
  • Packages
  • Access modifiers
  • Garbage Collection
  • Inner classes
  • Static import
  • Static constructor

Java Exception Handling

  • Exception handling
  • Java try-catch
  • Java throw
  • Java throws
  • Checked and Unchecked Exceptions
  • Jav try catch finally
  • Exception Examples
  • Exception Propagation

Collections Framework

  • Collections in Java
  • Java ArrayList
  • Java LinkedList
  • Java Vector
  • Java HashSet
  • Java LinkedHashSet
  • Java TreeSet
  • Java HashMap
  • Java TreeMap
  • Java LinkedHashMap
  • Java Queue
  • Java PriorityQueue
  • Java Deque
  • Comparable interface
  • Comparator interface
  • Collections Interview Questions

MORE ...

  • Java Scanner Class
  • Java 8 Features
  • Java 9 Features
  • Java Conversion
  • Java Date
  • Java Multithreading
  • Java I/O
  • Java Serialization
  • Java Regex
  • Java AWT
  • Java Swing
  • Java Enum
  • Java Annotations
  • Java main method
  • Java Interview Q

Copyright © 2012 – 2025 BeginnersBook . Privacy Policy . Sitemap