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
classMyDefinedExceptionextendsException{publicMyDefinedException(Stringstr){super(str);}}publicclassMyClass{publicstaticvoidshowMyName(Stringstr)throwsMyDefinedException{if(str.equals("What is your Name?"))thrownewMyDefinedException("My name is Blah Blah");}publicstaticvoidmain(Stringa[]){try{showMyName("What is your Name?");}catch(MyDefinedExceptionmde){mde.printStackTrace();}}}
close