Try Catch
Introduction
In a function, if an exception is occur , the exception object containing type and message will be created which is called throw an exception
The list of method is called when the exception is thrown is called Call Stack
The block of the functions is called Exception Handler
If the exception handler is not found when exception occur, the default handler will print the information and terminate the program
public void testVoid(){
int[] arr = new int[3];
int i = arr[3];
}
// Output:java.lang.ArrayIndexOutOfBoundsException: Index 3 out of bounds for length 3
// CallStack ...
We can add try catch in order to prevent from the termination of the program
try {
// block of code to monitor for errors
// the code you think can raise an exception
}
catch (ExceptionType1 exOb) {
// exception handler for ExceptionType1
}
catch (ExceptionType2 exOb) {
// exception handler for ExceptionType2
}
// optional
finally {
// block of code to be executed after try block ends
}
public void testVoid(){
try {
int[] arr = new int[3];
int i = arr[3];
}
catch(Exception exception){
System.out.println(exception.getMessage());
}
}
//Output: Index 3 out of bounds for length 3
Throw
// throw the exception to upper layer
// e.g service throw exception to controller, so that the function of
// controller can handle the exception which is come from controller
public void test() throws Exception{
try{
File file = new File("test.txt");
}
catch(FileNotFoundException e){
// can do additional handling to specific type of exception
throws e;
}
}
Try-With-Resource
The
try
-with-resources statement is atry
statement that declares one or more resources. A resource is an object that must be closed after the program is finished with it. Thetry
-with-resources statement ensures that each resource is closed at the end of the statement. Any object that implementsjava.lang.AutoCloseable
, which includes all objects which implementjava.io.Closeable
, can be used as a resource.Before using try-with-resource
try{
FileOutputStream os = new FileOutputStream( new File("test2.txt"));
byte[] b = {65,66,67,68,69};
os.write(b);
}
catch(IO Exception){
...
}
finally{
os.flush();
os.close();
}
// You must need to remember to close the os
After using try-with-resource
try(FileOutputStream os = new FileOutputStream( new File("test2.txt"));){
byte[] b = {65,66,67,68,69};
os.write(b);
os.flush();
}
catch(IO Exception){
...
}
Last updated
Was this helpful?