Python for C# Developers (try catch finally)

 

try, catch/except, finally is a necessary control flow in any modern programming language. Here is one in C#.

var obj = new MyObj();

try
{
    obj.func1("bad data"); // This line can cause an error.
    // Do some other work here if error didn't happen.
}
catch(SomeException exp)
{
   ExceptionHandler(exp);
}
finally
{
    obj.CleanUp();
}

Here is the sample in Python.

obj = MyObj()

try:
    obj.func1("bad data") # This line can cause an error.
except SomeError as exp:
    exception_handler(exp)
else:
    # Do some other work here if error didn't happen.
finally:
    obj.clean_up()

Notice that Python can have else clause but it’s not necessary to use it. I would use it if I want a very clear separation between “trying code” and the process after it.

There may be situations where you need to raise errors. You can simply use raise keyword like the example below.

raise ValueError("Entered value is not valid.")

There are quite a bit of builtin error types. They can be found in this document.

Lastly, if you need to create your own exception type, you can create a class that inherits from Exception class.

class MyError(Exception):
    pass

 

Author: admin

A software engineer in greater Seattle area

Leave a Reply

Your email address will not be published. Required fields are marked *