-2

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)

 }
}


Sud0
  • 55
  • 5
  • Also note that in some cases you'd want to catch a specific exception, throw another one or rethrow it (e.g. in client-server scenarios you'd catch an exception, log it and throw it again so your framework picks it up and sends it to the client). But in any case you might want to run some code after throwing the exception, i.e. the `finally` portion. Of course you _could_ do without finally by rearranging code and calling the same stuff multiple times but `finally` makes it so much easier. – Thomas Apr 15 '21 at 16:01
  • @Henry Twist not really. I also dont understand the answer. Why do I still use a finally block when I can also do a catch( Exception e ){}. Finally block: is always executed, no matter if an exception is thrown or not. But catch(Exception e) {} catches all exceptions and my program continues to execute. So I could do everything that is in the finally block also in my catch(Exception e) {} block. This is how I understand it. So I don't see any advantage of finally over catch(Exception e). – Sud0 Apr 15 '21 at 16:13
  • Well say you wanted to return in the catch, but you needed some resources to be closed before the method returns. The finally block then would be useful. To be honest though, it doesn't see a *massive* amount of use and there are always alternatives. – Henry Twist Apr 15 '21 at 16:21

2 Answers2

1

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.

Ryan
  • 1,762
  • 6
  • 11
  • Thanks for the "Try With Resources structure" tip, I didn't know that. But I could also omit the finally block in your example, right? I could write `catch (Exception e) { //print the exception reader.close() } reader.close()` But I think I understand it now when I write this. With finally I can save additional code. I don't need to check if an exception is thrown or not (like in my example, see my initial question). – Sud0 Apr 15 '21 at 16:24
  • In a try with resources, yes you would omit the finally block if all you would be doing is closing the reader. You could also omit the catch block and have the method throw the exception to the previous caller if you want to handle the exception higher up in the call stack. – Ryan Apr 15 '21 at 17:41
0

Ok..... For catch: catch is only executed if there is an exception while executing the code. This is for making code workable in unexpected situations. You will obviously not want to crash and stop your code in an unexpected way.

For finally: Imagine you are working with a database. Now, either there is a crash or not it is indeed a good practice to close the database connection after necessary processing has been done. Another example may be the file system. If you are dealing with files and either there is a crash or not you might always want to close the file stream after finishing your work or processing. You might ask why?

Well, this answer explains pretty well: https://stackoverflow.com/a/4111621/11928455

So, finally will obviously get executed either a crash happened or not. On the final block you will close connections to the database, stream of file....etc in a graceful way.