Java throws statement

In this chapter you will learn:

  1. How to use Java throws statement
  2. Syntax to use Java throws statement
  3. Example - Methods with throws clause

Description

If a method wants to throw an exception, it must specify this behavior.

Syntax

This is the general form of a method declaration that includes a throws clause:


type method-name(parameter-list) throws exception-list 
{ 
// body of method 
}

exception-list is a comma-separated list of the exceptions that a method can throw.

Example


public class Main {
  static void throwOne() throws IllegalAccessException {
    System.out.println("Inside throwOne.");
    throw new IllegalAccessException("demo");
  }//from   w ww  .jav a 2 s .  co  m

  public static void main(String args[]) {
    try {
      throwOne();
    } catch (IllegalAccessException e) {
      System.out.println("Caught " + e);
    }
  }
}

The code above generates the following result.

Next chapter...

What you will learn in the next chapter:

  1. How to use Java finally statement
  2. Syntax to use Java finally statement
  3. Note on Java finally statement
  4. Example - Java finally statement
Home »
  Java Tutorial »
    Java Langauge »
      Java Exception Handling
Java Exception
Java Exception types
Java try catch statement
Java throw statement
Java throws statement
Java finally statement
Java Built-in Exceptions
Java custom exception class
Java chained exceptions