Java Exception Handling – try, catch,
throw, throws
try block
The try block is used to enclose code that may cause an exception. It allows Java runtime to
detect errors and transfer control to catch. It improves stability and prevents abnormal
termination. Only risky code should be placed inside try. Multiple catch blocks can follow a
single try block to handle different exceptions.
Code
public class Main{
public static void main(String[] args){
try{
int a=10/0;
}catch(ArithmeticException e){
[Link]("Division by zero");
}
}
}
catch block
The catch block handles exceptions thrown inside try. It prevents program crash and allows
graceful recovery. Catch should be specific and ordered from child to parent exception
types.
Code
public class Main{
public static void main(String[] args){
try{
int[] a=new int[2];
a[5]=10;
}catch(ArrayIndexOutOfBoundsException e){
[Link]("Index error");
}
}
}
throw keyword
throw is used to manually throw an exception. It is useful in validations and custom error
handling. It creates an exception object and passes it to JVM.
Code
public class Main{
static void validate(int age){
if(age<18) throw new ArithmeticException("Not eligible");
}
public static void main(String[] args){
validate(15);
}
}
throws keyword
throws is used in method declaration to pass responsibility of handling exception to caller.
It avoids handling inside method and improves modularity.
Code
public class Main{
static void test() throws InterruptedException{
[Link](1000);
}
public static void main(String[] args) throws InterruptedException{
test();
}
}
Common Exceptions
ArrayIndexOutOfBoundsException
NullPointerException
StringIndexOutOfBoundsException
NumberFormatException
ArithmeticException
IOException
FileNotFoundException
ClassNotFoundException
InterruptedException
IllegalArgumentException
IllegalStateException
ConcurrentModificationException
IndexOutOfBoundsException
SecurityException
UnsupportedOperationException
StackOverflowError
OutOfMemoryError
EOFException
SQLException
ParseException
NoSuchElementException