HOLIDAY SALE! Save 50% on Membership with code HOLIDAY50. Save 15% on Mentorship with code HOLIDAY15.

2) Exception Handling Lesson

Java: Method "Throws" Exception

4 min to complete · By Ryan Desmond

The throws keyword is used in Java when a method is created and prepares for an Exception that it won't be able to handle. In the case that a method generates an exception and is unable to properly handle it, you can indicate that the given method throws the exception to the calling method.

Why Use the Throws Keyword?

If a method generates an Exception that it does not handle, the method must include a throws clause in the method signature. This is a common occurrence since it is often the case that the method where the Exception occurs does not know what it should do if/when an Exception occurs. In this case, you can throw the Exception back to the calling method and let the calling method do with it as it pleases. 

Syntax

A throws clause looks like the following:

public static int divide(int a, int b) throws ArithmeticException {...}

Example Throws Keyword Java

Below is an example of using the throws keyword in Java.

class Main {
  public static void main(String[] args){
    try {
      // you can see that the divide() method below 
      // "throws" an exception (potentially - based on input)
      // so you need to use a try-catch here to catch 
      // the exception that may be thrown
      int x = divide(4, 0);
    } catch(ArithmeticException exc){
      System.out.println(
        "an exception was thrown from the divide() method.");
    }
    System.out.println("all done");
  }

  // the divide() method will throw any exception 
  // that occurs back to the method
  // that called it - in this case, that's the 
  // main() method above
  public static int divide(int a, int b) 
      throws ArithmeticException {
    // this will generate an ArithmeticException
    return a/b;
  }
}

If the method divide generates an ArithmeticException exception, it will throw it back to the method that called it, in this case, the main() method. If the main() method does not handle the Exception, it will be thrown to the JVM, thus terminating the program with an unhappy Exception. Tisk tisk :)

Summary: What is the Throws Keyword in Java

  • The throws keyword is used in Java to indicate that a method may "throw" a generated exception back to the calling method
  • The calling method must therefore be ready to handle any exception it receives in a graceful manner
  • The throws keyword is placed inside the method signature

Syntax

Here's the syntax for the throws keyword, where you can substitute the variables starting with your or Your with your values.

public your_return_type your_method() throws YourException {...}