5

If I catch all exceptions;

try
{
    ... //code causes error
}
catch (Exception e)
{
   ...//handle all exceptions
}

So there is no need to use Finally block? since I catch all exceptions, the program will continue to execute the code after try-catch?

Another questions is, if use a finally block, how can I catch the errors happened in the final block itself? I mean it looks like we only need to put everything in the try and catch block which is in the very end?

2 Answers2

3

So there is no need to use Finally block?

The finally clause has very little to do with what, how and how many exceptions you catch. Think of the code that goes in a finally clause as clean up code that must be run independently of what happens inside the try clause. A typical scenario is the following (I'll use some C#7 for the fun of it):

(bool Succesful, object Result) TryDoSomethingDangerous()
{
    var someDisposableObject = new SomeDisposableObject();

    try
    {
        var result = someDisposableObject.DoSomethingDangerous(); //documented to be able to throw SomethingBadHappenedException
        return (true, result);
    }
    catch (SomethingBadHappenedException e)
    {
        Logger.Log(e);
        InformUserSomethingWentWrong(e);
        return (false, null);
    }
    finally
    {
        someDisposableObject.Dispose();
    }
}

since I catch all exceptions, the program will continue to execute the code after try-catch?

This is worrying. Yes if you catch all exceptions your code will keep running (how long is anyone's guess), but this is, in general, a very bad idea. You should only deal with exceptions you know how to fix and recover from. Swallowing exceptions just to keep trudging along is bound to end in disaster.

In general, catch (System.Exception) is a bad idea unless you are planning to simply log information and re throw immediately.

Another questions is, if use a finally block, how can I catch the errors happened in the final block itself? I mean it looks like we only need to put everything in the try and catch block which is in the very end?

Again, you are completely misunderstanding the execution flow in try-catch-finally. Code in finally is code that must run no matter what happens inside the try clause. You seem to believe that it's code that should only run if there is an exception.

In general, its better if code inside a finally clause is robust and does not throw exceptions itself. If, given the circumstances, this is not possible then the code inside the finally clause will need to have its own exception handling mechanism. In my case I try to avoid this kind of scenario and refactor code accordingly.

InBetween
  • 32,319
  • 3
  • 50
  • 90
1

enter image description here

In situations such as releasing resources, it is used twice instead of writing the same code (both try and catch). Such as closing the database connection and disposing of an object

Fatih Topcu
  • 132
  • 2
  • 3