Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Where should I catch exceptions when making use of '"using" keyword in the code?

Which one is better in structure?

class Program
{
    static void Main(string[] args)
    {
        try
        {
            using (Foo f = new Foo())
            {
                //some commands that potentially produce exceptions.
            }
        }
        catch (Exception ex)
        {
            Console.WriteLine(ex.Message);
        }
    }
}

or...

class Program
{
    static void Main(string[] args)
    {

        using (Foo f = new Foo())
        {
            try
            {
                //some commands that potentially produce exceptions.
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }
        }

    }
}
like image 532
xport Avatar asked Aug 03 '10 10:08

xport


People also ask

Where should you catch exceptions?

You should catch the exception when you are in the method that knows what to do. For example, forget about how it actually works for the moment, let's say you are writing a library for opening and reading files. Here, the programmer knows what to do, so they catch the exception and handle it.

Which keywords are used to handle exceptions?

The throw keyword is used to throw exceptions to the runtime to handle it. throws – When we are throwing an exception in a method and not handling it, then we have to use the throws keyword in the method signature to let the caller program know the exceptions that might be thrown by the method.

How do you catch exceptions in Python?

The try and except block in Python is used to catch and handle exceptions. Python executes code following the try statement as a “normal” part of the program. The code that follows the except statement is the program's response to any exceptions in the preceding try clause.

What is an exception How do you handle exceptions in Python?

In Python, exceptions can be handled using a try statement. The critical operation which can raise an exception is placed inside the try clause. The code that handles the exceptions is written in the except clause. We can thus choose what operations to perform once we have caught the exception.


1 Answers

Either is fine, depending on what you are going to do in the catch. If you need to use f in your catch then it needs to be within the using statement. However in your example there is no difference.

EDIT: As pointed out elsewhere it also depends on whether you are trying to catch just exceptions generated in the block following the using or including the object creation in the using statement. If it is in the block following the using then it is as I described. If you want to catch exceptions generated by Foo f = new Foo() then you need to use the first method.

like image 98
btlog Avatar answered Sep 21 '22 16:09

btlog