Python Tutorial menu

Python Try...Except

try and except let your program handle errors calmly instead of crashing.

What is an Exception?

An exception is an error that happens while the program is running. Without handling, Python stops and prints an error message.

Example

python
print(10 / 0)
Output
ZeroDivisionError: division by zero

try and except

Put risky code inside try. If an error happens, Python jumps to except:

Example

python
try:
    print(10 / 0)
except:
    print("Something went wrong")
print("Program continues")
Output
Something went wrong
Program continues

Catching Specific Errors

It is better to name the error you expect. You can have several except blocks:

Example

python
def divide(a, b):
    try:
        return a / b
    except ZeroDivisionError:
        return "Cannot divide by zero"
    except TypeError:
        return "Please give numbers only"

print(divide(10, 2))
print(divide(10, 0))
print(divide(10, "two"))
Output
5.0
Cannot divide by zero
Please give numbers only

A bare except: catches every error, even ones you did not expect, which can hide bugs. Name the exceptions whenever you can.

Common Exceptions

ExceptionWhen it happens
ValueErrorRight type but wrong value, like int("abc")
TypeErrorWrong type, like "5" + 5
ZeroDivisionErrorDividing by zero
IndexErrorList index that does not exist
KeyErrorDictionary key that does not exist
FileNotFoundErrorOpening a file that is not there
NameErrorUsing a variable that was never created

Getting the Error Message

Use as to store the error and print its message:

Example

python
try:
    age = int("twenty")
except ValueError as e:
    print("Error:", e)
Output
Error: invalid literal for int() with base 10: 'twenty'

else and finally

  • else runs only if no error happened
  • finally runs always, error or not. It is good for clean-up work.

Example

python
try:
    marks = int("85")
except ValueError:
    print("Not a number")
else:
    print("Marks saved:", marks)
finally:
    print("Check complete")
Output
Marks saved: 85
Check complete

A Safe Input Loop

Keep asking until the user types a valid number:

Example

python
while True:
    try:
        qty = int(input("Quantity: "))
        break
    except ValueError:
        print("Please type a whole number")
print("You ordered", qty)
Output
Quantity: five
Please type a whole number
Quantity: 5
You ordered 5

Raising Your Own Errors

Use raise to stop the program on purpose when something is not allowed:

Example

python
def set_age(age):
    if age < 0:
        raise ValueError("Age cannot be negative")
    return age

try:
    set_age(-3)
except ValueError as e:
    print(e)
Output
Age cannot be negative

Exercise

Exercise

Which block runs whether an error happened or not?

Learn Python with a teacher

Join the Python Programming course at Workownix, online or in Orangi Town, Karachi, and get a certificate.

See the course Ask on WhatsApp