How to make exceptions with 'try' and 'except' blocks in Python
Overview
We can make exceptions with the try and except blocks in Python as an easy way to handle error types such as ValueError and ZeroDivisionError.
Certain programs that accept input from a user will need the try and except blocks to avoid any probable error from user input.
Example
The program below requests the age of a user and returns an output. The expected input from the user is a numerical value.
age = int(input('what is your age? '))print(age)
Enter the input below
Explanation
In this example, the process finishes with exit code 0, which means that the program terminated successfully and there was no error.
Now, when a user gives an invalid input (e.g. twenty-two) instead of a numerical value, the output is as follows:
Output
What is your age? twenty two
ValueError: invalid literal for int() with base 10: 'twenty two'
Process finished with exit code 1
Explanation
As you can see in the terminal window, there is an error message,
ValueError, as well as
Process finished with exit code 1. This means that the program crashed and there was an error in the program.
As a good Python programmer, you should always anticipate these kinds of situations. You do not want to let your entire program crash just because a user entered an invalid input. To handle this situation, we can use the try and except blocks.
How to use the try and except blocks
When you use the try and except blocks, you have to follow these steps:
- Figure out the kind of error a user is likely to make. The most common error types are
ValueErrorandZeroDivision. - Instead of letting the program crash, introduce the
tryandexceptblocks in order to return an error message for the likely errors.
Example
Let’s write the program to check for Value error.
A
Value erroroccurs when a function receives an argument of the correct type but an inappropriate value.
# introducing the try blocktry:age = int(input('what is your age? '))print(age)# introducing the except block and the type of error the code might encounterexcept ValueError:print('Invalid value')
Output
What is your age? twenty two
Invalid value
Process finished with exit code 0
Explanation
As can be seen from the output above, the program terminates successfully because of exit code 0. Even though the user gives a wrong/invalid input (non-numerical input), the program does not crash. Instead, the program returns an error message to the user as a result of the except block in the code.
Example
Now, let’s write a program to check for ZeroDivisionError.
ZeroDivisionErroroccurs when a number is divided by zero or a number is modulo by zero.
# introducing the try blocktry:age = int(input('what is your age? '))# introducing another variblesnetworth = 5000resistance = networth/ageprint(resistance)# introducing the except block and the ZerDivisionErrorexcept ZeroDivisionError:print('Your age can never be 0.')except ValueError:print('Invalid value')
Output
what is your age? 0
your age can never be zero
Process finished with exit code 0
Explanation
The code above provides two exceptions for ValueError and ZeroDivisionError.
The user gives zero as input, but Python does not terminate the program during the execution. It returns an error message instead.