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
Home / java / Difference between throw and throws in java

Difference between throw and throws in java

By Chaitanya Singh

In this guide, we will discuss the difference between throw and throws keywords. Before going though the difference, refer my previous tutorials about throw and throws.

Throw vs Throws in java

1. Throws clause is used to declare an exception, which means it works similar to the try-catch block. On the other hand throw keyword is used to throw an exception explicitly.

2. If we see syntax wise than throw is followed by an instance of Exception class and throws is followed by exception class names.
For example:

throw new ArithmeticException("Arithmetic Exception");

and

throws ArithmeticException;

3. Throw keyword is used in the method body to throw an exception, while throws is used in method signature to declare the exceptions that can occur in the statements present in the method.

For example:
Throw:

...
void myMethod() {
   try {
      //throwing arithmetic exception using throw
      throw new ArithmeticException("Something went wrong!!");
   } 
   catch (Exception exp) {
      System.out.println("Error: "+exp.getMessage());
   }
}
...

Throws:

...
//Declaring arithmetic exception using throws
void sample() throws ArithmeticException{
   //Statements
}
...

4. You can throw one exception at a time but you can handle multiple exceptions by declaring them using throws keyword.
For example:
Throw:

void myMethod() {
   //Throwing single exception using throw
   throw new ArithmeticException("An integer should not be divided by zero!!");
}
..

Throws:

//Declaring multiple exceptions using throws
void myMethod() throws ArithmeticException, NullPointerException{
   //Statements where exception might occur
}

These were the main differences between throw and throws in Java. Lets see complete examples of throw and throws keywords.

Throw Example

To understand this example you should know what is throw keyword and how it works, refer this guide: throw keyword in java.

public class Example1{  
   void checkAge(int age){  
	if(age<18)  
	   throw new ArithmeticException("Not Eligible for voting");  
	else  
	   System.out.println("Eligible for voting");  
   }  
   public static void main(String args[]){  
	Example1 obj = new Example1();
	obj.checkAge(13);  
	System.out.println("End Of Program");  
   }  
}

Output:

Exception in thread "main" java.lang.ArithmeticException: 
Not Eligible for voting
at Example1.checkAge(Example1.java:4)
at Example1.main(Example1.java:10)

Throws Example

To understand this example you should know what is throws clause and how it is used in method declaration for exception handling, refer this guide: throws in java.

public class Example1{  
   int division(int a, int b) throws ArithmeticException{  
	int t = a/b;
	return t;
   }  
   public static void main(String args[]){  
	Example1 obj = new Example1();
	try{
	   System.out.println(obj.division(15,0));  
	}
	catch(ArithmeticException e){
	   System.out.println("You shouldn't divide number by zero");
	}
   }  
}

Output:

You shouldn't divide number by zero
❮ PreviousNext ❯

Posted Under: java | Tags: Exception-Handling

Comments

  1. prahalad says

    January 12, 2014 at 7:06 AM

    i m not understand the difference between throw and throws..plz help me..

    Reply
    • Chaitanya Singh says

      April 6, 2014 at 3:51 PM

      Hi Prahalad, Could you please let me know in which part you faced difficulties to understand? Try to go through the separate articles of throw keyword and throws clause and then go through the differences, you will be able to understand better then. Thanks!

      Reply
    • Hemanth Kumar says

      February 5, 2015 at 12:42 PM

      By using Throw keyword in java you cannot throw more than one exception but using throws you can declare multiple exceptions.
      I hope this solves your confusion.

      Reply
  2. Jagadeesh Verri says

    January 22, 2014 at 2:16 AM

    You should have explained the flow of execution when any program is given as a supporting example, that would make things easier and comfortable

    Reply
  3. fazeela says

    February 8, 2014 at 11:06 AM

    perfect explanation
    just what i was looking for
    Thank you

    Reply
  4. chandan says

    April 16, 2014 at 4:55 PM

    Sir, If we have only one Exception then which one better option to use (throw or throws)…….?

    Reply
    • Jamil says

      April 28, 2014 at 5:52 AM

      Single exception = Throw
      Multiple Exceptions = Throws

      Reply
    • Chaitanya Singh says

      August 11, 2014 at 4:03 AM

      Actually the usage of throw and throws is completely different. It depends whether you are throwing an exception or handling it. To throw an exception we use throw keyword while to handle (catch) an exception we use throws clause.

      Reply
      • gajanan says

        August 17, 2015 at 7:58 AM

        Give with example how to handle exception with throws keyword

        Reply
      • Nurseyit says

        December 15, 2016 at 2:16 AM

        yes you are right!!

        Reply
    • Kartik Sagar says

      January 30, 2015 at 4:29 PM

      Actually Throws keyword is used to throw the checked exceptions which a programmer doesn’t want to handle it so a programmer throws these exception so that compiler did not give an error but throw keyword is used to throw an built-in-exception or user defined exception explicitly so both concepts are different so go through these concepts separately and then read these differences then you will did not get any confusion.

      Reply
    • Sanjay says

      March 9, 2016 at 6:07 AM

      throws is best for both single and multiple exceptions.

      Reply
  5. Mayur says

    April 21, 2014 at 4:51 AM

    Thank You for the useful info .

    Reply
  6. phally says

    May 7, 2014 at 6:34 AM

    how many types of exception ?

    Reply
    • Chaitanya Singh says

      August 11, 2014 at 3:52 AM

      There are two types of exception: checked and unchecked. You can refer this article: https://beginnersbook.com/2013/04/java-checked-unchecked-exceptions-with-examples/

      Reply
  7. Dharam Jaswal says

    May 15, 2014 at 8:43 AM

    Realy very…..nice tutorial by you
    Thanks

    Reply
  8. sarika says

    August 6, 2014 at 9:10 AM

    Iam not getting why we use new keyword with throw……why there is need for this declaration?
    can any1 explain me?

    Reply
    • Chaitanya Singh says

      August 11, 2014 at 3:57 AM

      Refer the reply to Priya’s comment.

      Reply
  9. priya says

    August 8, 2014 at 12:58 PM

    why we declare -throw new exception?

    Reply
    • Chaitanya Singh says

      August 11, 2014 at 3:56 AM

      @Sarika and @Priya: the statement throw new Exception(“Something went wrong!!”); in the above program is throwing a custom exception with our own defined message “Something went wrong!!”. It is just an example to show that the code in try block is actually throwing an exception. Refer this article to learn more about throwing a custom exception: https://beginnersbook.com/2013/04/user-defined-exception-in-java/

      Reply
  10. Amit says

    August 10, 2014 at 4:32 AM

    What happens if you don’t call wait and notify from synchronized block?

    Reply
  11. ashfaq says

    August 18, 2014 at 11:26 AM

    sir , if we can handle all the exception by mentioning THROWS key word in main() method, then whats the use of throw, or why should we go individually to all the methods.?

    Reply
  12. rupali says

    August 21, 2014 at 9:02 AM

    in above comment u r saying “To throw an exception we use throw keyword while to handle (catch) an exception we use throws clause.”,but can u explain me 1 doubt ,although throw is an explicit creator,but still we have to handle that exception or that method using try catch where in that method we write throw new any …exception.

    and when we using throws clause that time also we have to handle that exception or method throwing an exception.

    that means in BOTH cases we are HANDLING the exception,is it right or not?

    Reply
  13. ramesh says

    August 29, 2014 at 3:39 AM

    how can we handle the exceptions without using catch,throw, and throws clause.
    I faced this question in one interview. kindly reply me….

    Reply
    • Vinodha g says

      November 12, 2014 at 4:59 AM

      @ramesh.. If u get the answer Please answer me to this question.

      Reply
      • shalini Gupta says

        July 20, 2015 at 12:26 PM

        by using try and finally only, we can handle an exception without using catch throw and throws.

        Reply
  14. Deepa says

    September 26, 2014 at 2:40 PM

    This is very useful. Good job on documenting these differences so well.! Thanks.

    Reply
  15. chandrakanth.B says

    October 21, 2014 at 5:22 PM

    hi sir, can u send still more java interview questions so that we will easy to face the any interviews.thanq…………

    Reply
    • Chaitanya Singh says

      October 23, 2014 at 5:38 AM

      Hello chandrakanth.B, Refer this article: https://beginnersbook.com/2013/05/java-interview-questions/

      Reply
  16. bindhu says

    October 23, 2014 at 7:22 AM

    i understood the throw and throws difference. i want what is what and simple explanation.

    Reply
    • Chaitanya Singh says

      November 15, 2014 at 8:34 AM

      I have provided the links of the detailed articles of throw and throws keyword at the beginning of this post. Please refer them and let me know if you have any questions.

      Reply
  17. sindhuja says

    October 24, 2014 at 8:47 AM

    what is the difference between exception and error?

    Reply
    • Vinodha g says

      November 12, 2014 at 4:56 AM

      Error is a compile time error it may be syntax error or else.. But exception occurs during the execution time it cannot get identified by compiler.

      Reply
  18. shradha patel says

    December 5, 2014 at 6:21 AM

    Does throw use for checked or unchecked exceptions………????
    Please let me know I am so confused.

    Reply
  19. hemavathi says

    December 12, 2014 at 10:51 AM

    class A{
    public void add()throws IOException
    {
    …….
    }
    class B extends A
    {
    public void add()throws Exception
    {
    ………….
    }
    }
    can we take like this?
    please explain me if we take like this what happen I faced this question in one interview.

    Reply
    • Prashant says

      September 7, 2016 at 5:47 PM

      @Hemavati, The program you written above is not possible because
      in ur prgrm the add() method is overrided right… Then overrided method should not change its declaration in any sub classes.. der Add() method id declared with the diff exception classes so it cannot possible…(throws different Exception ).

      But…
      We can declare different Exception with method body… only when Superclass method is having super Exception class and subclass has subclass of exception,,

      in your program Exception is super class and the IOexception is Sub class of Exception… hence Your program can rewritten like…

      class A{
      public void add()throws Exception
      {
      …….
      }
      class B extends A
      {
      public void add()throws IOException
      {
      ………….
      }
      }

      Hope you got my msg….

      Reply
  20. Arvind singh says

    February 28, 2015 at 6:53 PM

    Is it possible to handle the exception without using try-catch block and throws?..i am so confused bz this question was asked by interviewer….please help me.

    Reply
  21. Arvind singh says

    February 28, 2015 at 6:58 PM

    One more difference between throws and throw?
    Throw is associated with try-catch block whereas throws is declared with method declaration..
    if there is any mistakes…please respond me..thanks

    Reply
  22. dheer says

    March 7, 2015 at 8:13 PM

    I have a confusion, which of these two (throw and throws) are used to trigger any exception.

    Reply
  23. Durgesh says

    April 1, 2015 at 8:53 AM

    when use to throw and throws ..?

    Reply
  24. Tarang says

    June 23, 2015 at 7:04 AM

    using throw one can handle custom exception

    Reply
  25. rajesh says

    October 7, 2015 at 6:06 PM

    if there is a catch block to handle the exceptions then what is the need of throws block

    Reply
  26. Nawal Sah says

    February 17, 2016 at 7:06 AM

    I want to execute a few stmts (lets say stmt1,stmt2) which raise a checked exception(lets say BadException1). I want to execute stmt3,stmt4 no matter whether stmt1 and stmt2 fail or not. Also stmt3,stmt4 throws checked exception BadException2. Write a code block to demonstrate how you will ensure this.

    Reply
  27. Shubham says

    May 16, 2016 at 2:36 AM

    Is there any way to convert checked exception into unchecked ?

    Reply
  28. Farhana says

    August 17, 2016 at 8:06 AM

    when writing IO programs it forces to handle IOException at that time best way is to use throws clause.

    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 – 2022 BeginnersBook . Privacy Policy . Sitemap