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
Exception Handling: The basic way to cope with exception is using try ...catch.
The Syntax for using try...catch is
try{
...
...
Code have to monitor for exception
...
...
}catch(Exception e){
...
Exception action code
...
}
Here is an easy example to demonstrate the above case..
public
class ExceptionExp2 {
public
static
void main(String args[]){
String strArray[] = {"This","is","an","example","of","Java","exception" };
try{
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]);
}catch(ArrayIndexOutOfBoundsException exp){
System.out.println("Exception Occurred");
}
System.out.println("This will execute");
}
}
If you run the above code it will give the following output …
This
is
example
of
Java
exception
Exception Occurred
This will execute
So exception is handled here by printing a message "Exception Occurred" and the program continues to execute the codes after the try ... catch block instead of terminating.