0% found this document useful (0 votes)
37 views

Python Language: Exceptions: The FOSSEE Group

This document discusses exceptions in Python. Python uses exceptions to signal errors and provides standard exceptions like SyntaxError. Users can also define their own exceptions. Exceptions can be caught using try/except blocks to handle errors gracefully. Specific exceptions should be caught rather than using a blanket exception. Finally blocks ensure cleanup code is always executed.

Uploaded by

Arvind Garg
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
37 views

Python Language: Exceptions: The FOSSEE Group

This document discusses exceptions in Python. Python uses exceptions to signal errors and provides standard exceptions like SyntaxError. Users can also define their own exceptions. Exceptions can be caught using try/except blocks to handle errors gracefully. Specific exceptions should be caught rather than using a blanket exception. Finally blocks ensure cleanup code is always executed.

Uploaded by

Arvind Garg
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 24

Python language: exceptions

The FOSSEE Group


Department of Aerospace Engineering
IIT Bombay

Mumbai, India

FOSSEE Team (IIT Bombay) Exceptions 1 / 20


Motivation

How do you signal errors to a user?

FOSSEE Team (IIT Bombay) Exceptions 2 / 20


Exceptions

Python’s way of notifying you of errors


Several standard exceptions: SyntaxError,
IOError etc.
Users can also raise errors
Users can create their own exceptions
Exceptions can be “caught” via try/except
blocks

FOSSEE Team (IIT Bombay) Exceptions 3 / 20


Exceptions: examples

In []: while True print(’Hello world’)

File "<stdin>", line 1, in ?


while True print(’Hello world’)
^
SyntaxError: invalid syntax

FOSSEE Team (IIT Bombay) Exceptions 4 / 20


Exceptions: examples

In []: while True print(’Hello world’)

File "<stdin>", line 1, in ?


while True print(’Hello world’)
^
SyntaxError: invalid syntax

FOSSEE Team (IIT Bombay) Exceptions 4 / 20


Exceptions: examples

In []: print(spam)

Traceback (most recent call last):


File "<stdin>", line 1, in <module>
NameError: name ’spam’ is not defined

FOSSEE Team (IIT Bombay) Exceptions 5 / 20


Exceptions: examples

In []: print(spam)

Traceback (most recent call last):


File "<stdin>", line 1, in <module>
NameError: name ’spam’ is not defined

FOSSEE Team (IIT Bombay) Exceptions 5 / 20


Exceptions: examples

In []: 1 / 0

Traceback (most recent call last):


File "<stdin>", line 1, in <module>
ZeroDivisionError: integer division
or modulo by zero

FOSSEE Team (IIT Bombay) Exceptions 6 / 20


Exceptions: examples

In []: 1 / 0

Traceback (most recent call last):


File "<stdin>", line 1, in <module>
ZeroDivisionError: integer division
or modulo by zero

FOSSEE Team (IIT Bombay) Exceptions 6 / 20


Exceptions: examples

In []: ’2’ + 2

Traceback (most recent call last):


File "<stdin>", line 1, in ?
TypeError: cannot concatenate ’str’ and ’

FOSSEE Team (IIT Bombay) Exceptions 7 / 20


Exceptions: examples

In []: ’2’ + 2

Traceback (most recent call last):


File "<stdin>", line 1, in ?
TypeError: cannot concatenate ’str’ and ’

FOSSEE Team (IIT Bombay) Exceptions 7 / 20


Processing user input

prompt = ’Enter a number(Q to quit): ’


a = input(prompt)

num = int(a) if a != ’Q’ else 0


What if the user enters some other alphabet?

FOSSEE Team (IIT Bombay) Exceptions 8 / 20


Handling Exceptions
Python provides a try and except clause.
prompt = ’Enter a number(Q to quit): ’
a = input(prompt)
try:
num = int(a)
print(num)
except:
if a == ’Q’:
print("Exiting ...")
else:
print("Wrong input ...")

FOSSEE Team (IIT Bombay) Exceptions 9 / 20


Handling Exceptions a little better
Use specific exceptions; avoid blanket except clauses
prompt = ’Enter a number(Q to quit): ’
a = input(prompt)
try:
num = int(a)
print(num)
except ValueError:
if a == ’Q’:
print("Exiting ...")
else:
print("Wrong input ...")

FOSSEE Team (IIT Bombay) Exceptions 10 / 20


Exceptions: examples

prompt = "Enter a number: "


while True:
try:
x = int(input(prompt))
break
except ValueError:
print("Invalid input, try again...")

FOSSEE Team (IIT Bombay) Exceptions 11 / 20


Catching multiple exceptions

while True:
try:
data = input()
x = int(data.split(’,’)[1])
break
except IndexError:
print(’Input at least 2 values.’)
except ValueError:
print("Invalid input, try again...")

FOSSEE Team (IIT Bombay) Exceptions 12 / 20


Catching multiple exceptions

data = input()
try:
x = int(data.split(’,’)[1])
except (ValueError, IndexError):
print("Invalid input ...")

FOSSEE Team (IIT Bombay) Exceptions 13 / 20


try, except, else

while True:
try:
data = input()
x = int(data.split(’,’)[1])
except (ValueError, IndexError):
print("Invalid input ...")
else:
print(’All is well!’)
break

FOSSEE Team (IIT Bombay) Exceptions 14 / 20


Some comments

In practice NEVER use blanket except clauses


Always catch specific exceptions

FOSSEE Team (IIT Bombay) Exceptions 15 / 20


Exceptions: raising your exceptions

>>> raise ValueError("your error message")


Traceback (most recent call last):
File "<stdin>", line 2, in ?
ValueError: your error message

FOSSEE Team (IIT Bombay) Exceptions 16 / 20


Exceptions: try/finally

while True:
try:
x = int(input(prompt))
break
except ValueError:
print("Invalid number, try again...")
finally:
print("All good!")
Always runs the finally clause!

FOSSEE Team (IIT Bombay) Exceptions 17 / 20


Exceptions: try/finally
def f(x):
try:
y = int(x)
return y
except ValueError:
print(x)
finally:
print(’finally’)

>>> f(1)
>>> f(’a’)
Always runs the finally clause!
FOSSEE Team (IIT Bombay) Exceptions 18 / 20
Summary

Catching exceptions with try/except


Catching multiple exceptions
Cleanup with finally
Raising your own exceptions

FOSSEE Team (IIT Bombay) Exceptions 19 / 20


What next?

Only covered the very basics


More advanced topics remain
Read the official Python tutorial:
docs.python.org/tutorial/

FOSSEE Team (IIT Bombay) Exceptions 20 / 20

You might also like