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();

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

Here is the sample in Python.

obj = MyObj()

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

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):


Author: admin

A software engineer in greater Seattle area

Leave a Reply

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