Jump to content

Java Programming/Keywords/throws

From Wikibooks, open books for an open world

throws is a Java keyword. It is used in a method definition to declare the Exceptions to be thrown by the method.

Syntax:

public myMethod() throws MyException1, MyException2
{MyException1
  ...
}

Example:

Computer code
class MyDefinedException extends Exception
 {
  public MyDefinedException(String str) 
  {
     super(str);
  }   
 }

 public class MyClass
 {
    public static void showMyName(String str) throws MyDefinedException
    {
          if(str.equals("What is your Name?"))
                throw new MyDefinedException("My name is Blah Blah");
    }
    public static void main(String a[])
    {
       try
       {
          showMyName("What is your Name?");
       }
       catch(MyDefinedException mde)
       {
          mde.printStackTrace();
       }
     }
 }