Java by Example: Exception Handling, creating custom exception class
Java by Example: Exception handling – throw custom Exception
Java By Example: Exception Handling – Throwing exception from method
Java by Example: Exception handling – Basic Exception Handling example ‘try catch’
Java by Example: Exception Handling – Java Exception Basics
The second way of exception handling is throwing the exception. This is done by adding throws with method name.
Syntax of throwing exception from method is
access_modifier return_type method_name(arguments) throws exception_list{
}
Here is a practical example of doing this..
public
class ExceptionExp3 {
public
static
void main(String args[]){
ExceptionExp3 excpExp = new ExceptionExp3();
try{
excpExp.tryThrows();
}catch(ArrayIndexOutOfBoundsException ae){
System.out.println("Exception Caught");
}
}
public
void tryThrows() throws ArrayIndexOutOfBoundsException{
String strArray[] = {"This","is", "an", "example", "of", "Java","exception" };
System.out.println(strArray[0]);
System.out.println(strArray[1]);
System.out.println(strArray[3]);
System.out.println(strArray[4]);
System.out.println(strArray[5]);
System.out.println(strArray[6]);
System.out.println(strArray[7]);
System.out.println("This statement wont execute");
}
}
The ArrayIndexOutOfBoundsException is thrown from method tryThrows() instead of handling the exception. In this case when exception occurred in tryThrows() method instead of terminating the program this method throw the exception to caller.
This program will give the following output..
This
is
example
of
Java
exception
Exception Caught