# 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

```java
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

```java
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
}
```

```java
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

```java
// 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 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.
* &#x20;Before using  try-with-resource

```java
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

```java
try(FileOutputStream os = new FileOutputStream( new File("test2.txt"));){
    byte[] b = {65,66,67,68,69};
    os.write(b);
    os.flush();
}
catch(IO Exception){
    ...
}
```
