No Try Catch but Try Except

In other programming languages, the keywords when referring to try and except blocks of code are “try” and “catch”. In Python 3, the keyword for “catch” is actually “except”. So, it is called a Try and Except block of code. But what does it do?

Example of a ValueError Exception

Sometimes, when you want to do an operation but you don’t know if it’s going to work or not, we use exception handling.

As a very basic example, consider that we are validating a user’s input.

text = input('age: ')

Say, the age has to strictly consist of numbers and not text or a string of numbers. In that case, we introduce a new variable. We can call this variable number and do the following to convert our text into integers and then print this to the screen:

text =input('age: ')

number = int(text)
print(number)

After doing all this, when we type in “hey” in the username slot, the program will crash with a ValueError: invalid literal for int() with base 10 ‘hey’ error. Because it is unable to convert this text into numbers.

In this case, we use a try and except block to tell users to input something else rather than having the entire program just crash. We can add the try block to our code this way:

Catching a ValueError Exception in Python 3

If you run the code with only try: without an except: command you will get a syntax error at compile time saying “SyntaxError: unexpected EOF while parsing”.

text = input('age: ')
try:
    number = int(text)
    print(number)
except ValueError:
    print("hey age should be a number")

The above shows how you can catch a ValueError. But what if you want to catch a generic error?

How To Create your own Exception in Python3?

You need to create a class as follows and inherit from Exception or BaseException.

class ShouldBePositive(Exception):
    pass

The above is the bare minimum for an exception.

How To Add Multiple Except Clauses and Chain Exceptions?

You can add multiple except clauses and also chain exceptions by Raise-ing an exception as follows:

class ShouldBePositive(Exception):
    pass

text = input('age: ')
try:
    number = int(text)
    print(number)
    if number < 0:
        raise ShouldBePositive
except ValueError:
    print("hey age should be a number")
except ShouldBePositive:
    print("Age can't be negative my dude")

How To Catch All Exceptions In Python 3?

In Python 3 all Exceptions inherit from the base class BaseException. The builtin Exceptions like ArithmeticException inherit from Exception which then inherits from BaseException. So you can do the following to catch all exceptions.

class ShouldBePositive(Exception):
    pass

text = input('age: ')
try:
    number = int(text)
    print(number)
    if number < 0:
        raise ShouldBePositive
except BaseException:
    print("something went wrong")

Final Words

This is a small note on exceptions but I would suggest you do further reading on its intricacies at https://docs.python.org/3/tutorial/errors.html and also if you want to learn how to test exceptions in unit tests checkout: https://docs.python.org/3/library/unittest.html

If you would like to learn more Python check out this certificate course by Google: IT Automation with Python