Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
2 views

Python Tutorial_ Exception Handling

The document provides an overview of exception handling in Python, explaining how to manage errors during program execution using try, except, and finally clauses. It illustrates the concept with examples, including custom exceptions and the use of else clauses. The tutorial aims to equip learners with the knowledge to write robust code that can handle various error scenarios effectively.

Uploaded by

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

Python Tutorial_ Exception Handling

The document provides an overview of exception handling in Python, explaining how to manage errors during program execution using try, except, and finally clauses. It illustrates the concept with examples, including custom exceptions and the use of else clauses. The tutorial aims to equip learners with the knowledge to write robust code that can handle various error scenarios effectively.

Uploaded by

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

Python Course

Home Python 2 Tutorial Python 3 Tutorial Advanced Topics Numerical Programming Machine Learning Tkinter Tutorial Contact

Previous Chapter: Iterators and Generators


Next Chapter: Tests, DocTests, UnitTests

Errors and Exceptions


Follow Bernd Klein,
the author of this
Exception Handling website, at Google+:
Bernd Klein on
Python 3 Google
Tutorial An exception is an error that happens during the execution of a program. Exceptions are known to non-programmers as instances that do not conform to a general rule. The name
Bernd Klein on
"exception" in computer science has this meaning as well: It implies that the problem (the exception) doesn't occur frequently, i.e. the exception is the "exception to the rule".
The Origins of Facebook
Exception handling is a construct in some programming languages to handle or deal with errors automatically. Many programming languages like C++, Objective-C, PHP, Java,
Python Ruby, Python, and many others have built-in support for exception handling.
Starting with
Error handling is generally resolved by saving the state of execution at the moment the error occurred and interrupting the normal flow of the program to execute a special function Search this website:
Python: The
or piece of code, which is known as the exception handler. Depending on the kind of error ("division by zero", "file open error" and so on) which had occurred, the error handler can
Interactive Shell
"fix" the problem and the programm can be continued afterwards with the previously saved data. Go
Executing a
Script
This topic in German
Indentation / Deutsche
Data Types and Exception Handling in Python Übersetzung:
Variables Ausnahmebehandlung
Operators Exceptions handling in Python is very similar to Java. The code, which harbours the risk of an exception, is embedded in a try block. But whereas in Java exceptions are caught by catch clauses, we have statements
Sequential Data introduced by an "except" keyword in Python. It's possible to create "custom-made" exceptions: With the raise statement it's possible to force a specified exception to occur. Python 3
Types: Lists and
Let's look at a simple example. Assuming we want to ask the user to enter an integer number. If we use a input(), the input will be a string, which we have to cast into an integer. If the input has not been a valid
Strings integer, we will generate (raise) a ValueError. We show this in the following interactive session: This is a tutorial in
List Python3, but this
Manipulations >>> n = int(input("Please enter a number: ")) chapter of our course
Shallow and Please enter a number: 23.5 is available in a
Traceback (most recent call last): version for Python
Deep Copy
File "<stdin>", line 1, in <module> 2.x as well:
Dictionaries ValueError: invalid literal for int() with base 10: '23.5' Exception Handling in
Sets and Frozen Python 2.x
Sets With the aid of exception handling, we can write robust code for reading an integer from input:
An Extensive Training Classes
while True:
Example Using try:
Sets n = input("Please enter an integer: ") This website aims at
input via the n = int(n) providing you with
break
keyboard educational material
except ValueError:
Conditional print("No valid integer! Please try again ...") suitable for self-
Statements print("Great, you successfully entered an integer!") learning.
Loops, while Nevertheless, it is
It's a loop, which breaks only, if a valid integer has been given. faster and more
Loop
The example script works like this: efficient to attend a
For Loops
The while loop is entered. The code within the try clause will be executed statement by statement. If no exception occurs during the execution, the execution will reach the break statement and the while loop will be "real" Python course
Difference in a classroom, with
left. If an exception occurs, i.e. in the casting of n, the rest of the try block will be skipped and the except clause will be executed. The raised error, in our case a ValueError, has to match one of the names after
between except. In our example only one, i.e. "ValueError:". After having printed the text of the print statement, the execution does another loop. It starts with a new input(). an experienced
interators und trainer. So why not
Iterables An example usage could look like this: attend one of the live
Output with Print Python courses
$ python integer_read.py
Formatted output
Please enter an integer: abc
with string No valid integer! Please try again ...
modulo and the Please enter an integer: 42.0
format method No valid integer! Please try again ...
Please enter an integer: 42
Functions
Great, you successfully entered an integer!
Recursion and $
Recursive
Functions
Parameter
Passing in Multiple Except Clauses
Functions
Namespaces A try statement may have more than one except clause for different exceptions. But at most one except clause will be executed. in Strasbourg, Paris,
Global and Local London, Berlin,
Our next example shows a try clause, in which we open a file for reading, read a line from this file and convert this line into an integer. There are at least two possible exceptions: Munich, Hamburg,
Variables
Frankfurt, or Lake
Decorators an IOError Constance by Bernd
Memoization with ValueError Klein, the author of
Decorators this tutorial?
Read and Write Just in case we have an additional unnamed except clause for an unexpected error:
Files import sys
Modular In-house
Programming try: Training
f = open('integers.txt')
and Modules
s = f.readline()
Courses
Packages in i = int(s.strip())
Python except IOError as e: If you like it, we will
Regular errno, strerror = e.args come to your
print("I/O error({0}): {1}".format(errno,strerror)) company or institute
Expressions
# e can be printed directly without using .args: and provide a special
Regular # print(e)
training for your
Expressions, except ValueError:
print("No valid integer in line.") employees, as we've
Advanced
except: done it many times in
Lambda print("Unexpected error:", sys.exc_info()[0]) Amsterdam (The
Operator, Filter, raise Netherlands), Berlin
Reduce and Map (Germany), Bern
List The handling of the IOError in the previous example is of special interest. The except clause for the IOError specifies a variable "e" after the exception name (IOError). The variable "e" is bound to an exception (Switzerland), Basel
Comprehension instance with the arguments stored in instance.args. (Switzerland), Zurich
If we call the above script with a non-existing file, we get the message: (Switzerland),
Iterators and
Frankfurt (Germany),
Generators I/O error(2): No such file or directory
Locarno
Exception
(Switzerland), Den
Handling And if the file integers.txt is not readable, e.g. if we don't have the permission to read it, we get the following message:
Haag (The Hague),
Tests, DocTests, Hamburg, Munich
I/O error(13): Permission denied
UnitTests (Germany),
Object Oriented An except clause may name more than one exception in a tuple of error names, as we see in the following example: Bucharest (Romania),
Programming Toronto (Canada),
Class and try: Edmonton (Canada),
f = open('integers.txt') and many other
Instance s = f.readline() cities. We do training
Attributes i = int(s.strip())
courses in England,
Properties vs. except (IOError, ValueError):
print("An I/O error or a ValueError occurred") Switzerland,
getters and Liechtenstein,
except:
setters print("An unexpected error occurred") Austria, Germany,
Inheritance raise France, Belgium, the
Multiple Netherlands,
Inheritance Luxembourg,
Magic Methods We want to demonstrate now, what happens, if we call a function within a try block and if an exception occurs inside the function call: Romania, UK, Italy,
Spain and other
and Operator
def f(): locations in Europe
Overloading x = int("four") and in Canada.
OOP, Inheritance
Example try:
f() This way you will get
Slots except ValueError as e: a perfect training up
Classes and print("got it :-) ", e) to your needs and it
Class Creation will be extremely cost
Road to efficient as well.
print("Let's get on")
Metaclasses
Contact us so we can
Metaclasses We learn from the above result that the function catches the exception: find the ideal course
Metaclass Use
to meet your needs.
Case: Count got it :-) invalid literal for int() with base 10: 'four'
Let's get on
Function Calls
Abstract Classes We will extend our example now so that the function will catch the exception directly: Skilled Python
Programmers
def f():
Exceptions try:
x = int("four") You are looking for
except ValueError as e: experienced Python
"Nothing travels print("got it in the function :-) ", e) developers or
faster than the speed programmers? We
of light with the try: can help you, please
possible exception of f() contact us.
bad news, which except ValueError as e:
print("got it :-) ", e)
obeys its own special Quote of the
laws." (Douglas Day:
Adams) print("Let's get on")
"General principles
"It's easy to make
should not be based As we have expected, the exception will be caught inside of the function and not in the callers exception:
mistakes that only
on exceptional
got it in the function :-) invalid literal for int() with base 10: 'four' come out much later,
cases." (Robert J.
Let's get on after you've already
Sawyer)
implemented a lot of
We add now a "raise", which generates the ValueError again, so that the exception will be propagated to the caller: code. You'll realize
Oh I should have
This website is
def f(): used a different type
supported by: try: of data structure.
x = int("four")
Start over from
except ValueError as e:
Linux and Python scratch" (Guido Van
print("got it in the function :-) ", e)
Training Courses raise Rossum)

try:
f()
except ValueError as e:
print("got it :-) ", e)

print("Let's get on")


Data Protection
Declaration
We will get the following result:
Data Protection
got it in the function :-) invalid literal for int() with base 10: 'four' Declaration
got it :-) invalid literal for int() with base 10: 'four'
Let's get on

Custom-made Exceptions

It's possible to create Exceptions yourself:

>>> raise SyntaxError("Sorry, my fault!")


Traceback (most recent call last):
File "<stdin>", line 1, in <module>
SyntaxError: Sorry, my fault!

The best or the Pythonic way to do this, consists in defining an exception class which inherits from the Exception class. You will have to go through the chapter on "Object Oriented Programming" to fully understand
the following example:

class MyException(Exception):
pass

raise MyException("An exception doesn't always prove the rule!")

If you start this program, you will get the following result:

$ python3 exception_eigene_klasse.py
Traceback (most recent call last):
File "exception_eigene_klasse.py", line 4, in <module>
raise MyException("Was falsch ist, ist falsch!")
__main__.MyException: An exception doesn't always prove the rule!

Clean-up Actions (try ... finally)

So far the try statement had always been paired with except clauses. But there is another way to use it as well. The try statement can be followed by a finally clause. Finally clauses are called clean-up or
termination clauses, because they must be executed under all circumstances, i.e. a "finally" clause is always executed regardless if an exception occurred in a try block or not.
A simple example to demonstrate the finally clause:

try:
x = float(input("Your number: "))
inverse = 1.0 / x
finally:
print("There may or may not have been an exception.")
print("The inverse: ", inverse)

Let's look at the output of the previous script, if we first input a correct number and after this a string, which is raising an error:

bernd@venus:~/tmp$ python finally.py


Your number: 34
There may or may not have been an exception.
The inverse: 0.0294117647059
bernd@venus:~/tmp$ python finally.py
Your number: Python
There may or may not have been an exception.
Traceback (most recent call last):
File "finally.py", line 3, in <module>
x = float(input("Your number: "))
ValueError: invalid literal for float(): Python
bernd@venus:~/tmp$

Combining try, except and finally

"finally" and "except" can be used together for the same try block, as can be seen the following Python example:

try:
x = float(input("Your number: "))
inverse = 1.0 / x
except ValueError:
print("You should have given either an int or a float")
except ZeroDivisionError:
print("Infinity")
finally:
print("There may or may not have been an exception.")

The output of the previous script, if saved as "finally2.py", for various values looks like this:

bernd@venus:~/tmp$ python finally2.py


Your number: 37
There may or may not have been an exception.
bernd@venus:~/tmp$ python finally2.py
Your number: seven
You should have given either an int or a float
There may or may not have been an exception.
bernd@venus:~/tmp$ python finally2.py
Your number: 0
Infinity
There may or may not have been an exception.
bernd@venus:~/tmp$

else Clause

The try ... except statement has an optional else clause. An else block has to be positioned after all the except clauses. An else clause will be executed if the try clause doesn't raise an exception.

The following example opens a file and reads in all the lines into a list called "text":

import sys
file_name = sys.argv[1]
text = []
try:
fh = open(file_name, 'r')
text = fh.readlines()
fh.close()
except IOError:
print('cannot open', file_name)

if text:
print(text[100])

This example receives the file name via a command line argument. So make sure that you call it properly: Let's assume that you saved this program as "exception_test.py". In this case, you have to call it with

python exception_test.py integers.txt

If you don't want this behaviour, just change the line "file_name = sys.argv[1]" to "file_name = 'integers.txt'".

The previous example is nearly the same as:

import sys
file_name = sys.argv[1]
text = []
try:
fh = open(file_name, 'r')
except IOError:
print('cannot open', file_name)
else:
text = fh.readlines()
fh.close()

if text:
print(text[100])

The main difference is that in the first case, all statements of the try block can lead to the same error message "cannot open ...", which is wrong, if fh.close() or fh.readlines() raise an error.

Previous Chapter: Iterators and Generators


Next Chapter: Tests, DocTests, UnitTests

© 2011 - 2018, Bernd Klein, Bodenseo; Design by Denise Mitchinson adapted for python-course.eu by Bernd Klein

You might also like