javaexceptiontry-catchfinally

catch (Exception e) {} vs finally {}


I am trying to understand and use exceptions.

why use finally? Instead of finally I could also do a catch(Exception e){}. This way my program never crashes and the code after the catch is always executed. Additionally I could add an if/else after the try and catch to check if an exception was thrown. This way my program would never crash and the if/else creates a standard behavior.

E.g. pseudo-code:

public void enterAndPrintANumber() {

boolean exception = false;
int number = 0;

try { 

System.out.println("Please enter a Number")
number = BufferedReader.readLine();

} catch(NumberFormatException e) {

System.out.println("Please enter a number")

}
 catch(Exception e) {

 System.out.println("An error has occurred")
 exception = true;

}

if(exception) {

System.out.println("Action will be restarted")
this.enterAndPrintANumber();

 } else {

 System.out.println("Your Number is "+number)

 }
}



Solution

  • In a nutshell try/catch/finally is interpreted as code you want to attempt, what to do if something goes wrong, and cleanup code at the the end. The most common use for a finally block is to close resources you're done with them. So you could have a block like:

    Reader reader = null;
    try {
      reader = new StringReader("test");
      //do stuff with reader
    } catch (Exception e) {
       //print the exception, log it, do something.
    } finally {
       reader.close()
    }
    

    Now, this use case has been mostly deprecated with the addition of the Try With Resources structure that automatically closes AutoClosable interface.

    Another use case would be if you're using things like Semaphores for synchronization purposes. In your try{} block you would acquire() the semaphore, and in your finally block you would release it.