Errors and Exceptions
When you write a Python program without following its syntax rules, you’ll encounter errors when you run it. Python will inform you that your code isn’t working and provide error details. For example, see what happens if you try to define a string in Python with quotes on only one side:
my_string = "Hello, world.
Traceback (most recent call last):
File "error.py", line 1
my_string = "Hello, world.
^
SyntaxError: EOL while scanning string literal
This message indicates a syntax error in your program. Syntax errors are critical; a program with them cannot run. When you try to run a program with a syntax error, Python will notify you.
The message will tell you the file where the error occurred, the line number, and the error type. Errors may seem intimidating, but they happen often.
If there’s an error in your code, go to the line number where the problem occurred and figure out what went wrong. In this example, check the first line. You’ll notice it only contains opening quotes. To fix this, close the quotes at the end of the line and rerun the program.
Python has two types of errors: syntax errors and exceptions. An exception is any error that isn’t a syntax error. Unlike syntax errors, exceptions aren’t always fatal.
ZeroDivisionError is an example of an exception that occurs when someone tries to divide by zero, if you, as a programmer, haven’t restricted such a possibility.
As you learn programming, you’ll frequently encounter syntax errors and exceptions, but their frequency will decrease over time. Remember, when you face a syntax error or exception, go to the line where the problem occurred and examine it until you find a solution.
Exception Handling
Suppose you wrote a program that takes two numbers from the user and outputs the result of dividing the first number by the second:
a = input("Enter a number: ")
b = input("Enter another number: ")
a = int(a)
b = int(b)
print(a / b)
The program will work. However, if the user enters 0 as the second number, you’ll encounter an error:
Traceback (most recent call last):
File "division.py", line 5
ZeroDivisionError: division by zero
You can’t just hope the user won’t enter 0. A great way to handle this situation is exception handling—a tool that lets you “catch” exceptions if they occur and decide what to do next.
The keywords try and except are used for exception handling. With exception handling, if the user enters 0 as the second number, the program can display a message about the inadmissibility of entering zero.
All exceptions in Python are objects, so you can use them in your programs. A list of built-in exceptions can be found here. If you think your code might generate an exception, use a compound statement with the keywords try and except to catch it.
The try block contains code that might generate an exception. The except block contains code that will only execute if an exception occurs within the try block. Below is an example of using exception handling where the program doesn’t terminate when 0 is entered as the second number:
try:
a = input("Enter a number: ")
b = input("Enter another number: ")
a = int(a)
b = int(b)
print(a / b)
except ZeroDivisionError:
print("b cannot be zero!")
This program will catch the ZeroDivisionError exception and transfer control to the except block, where we display a message about the inadmissibility of entering 0.
Your program will also terminate with an error if the user enters a string that Python can’t convert to an integer. Try entering a word instead of a number, and you’ll see an error message like this:
Traceback (most recent call last):
File "division.py", line 3
ValueError: invalid literal for int() with base 10: 'word'
This can be fixed by catching both types of exceptions:
try:
a = input("Enter a number: ")
b = input("Enter another number: ")
a = int(a)
b = int(b)
print(a / b)
except ZeroDivisionError:
print("b cannot be zero!")
except ValueError:
print("Number input error")
Do not use variables defined in the try statement in the except statement, as an exception might occur before the variable is defined, and using the except statement will generate an exception inside it.
try:
10 / 0
c = "I will never be defined."
except ZeroDivisionError:
print(c)
Such a program will end with an error:
Traceback (most recent call last):
File "zero.py", line 5
NameError: name 'c' is not defined