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
}

Throw

Try-With-Resource

  • The try-with-resources statement is a try statement that declares one or more resources. A resource is an object that must be closed after the program is finished with it. The try-with-resources statement ensures that each resource is closed at the end of the statement. Any object that implements java.lang.AutoCloseable, which includes all objects which implement java.io.Closeable, can be used as a resource.

  • Before using try-with-resource

  • After using try-with-resource

Last updated

Was this helpful?