Python Exception Handling - Try, Except and Finally PDF
Python Exception Handling - Try, Except and Finally PDF
Python Exception Handling - Try, Except and Finally PDF
Contents
Catching Speci c
Exceptions in Python
PYTHON TUTORIAL Python Exception Handling - Try, Except and Finally Raising Exceptions
In this article, you'll learn how to handle exceptions in your Python program using try, try... nally
Python Introduction
except and finally statements. This will motivate you to write clean, readable and efficient
Python Flow Control
code in Python.
Python Functions
Python Datatypes
Python Files
-- Python Directory
-- Python Exception
Python Object & Class When these exceptions occur, it causes the current process to stop and passes it to the
Python Advanced Topics calling process until it is handled. If not handled, our program will crash.
Python Date and time
For example, if function A calls function B which in turn calls function C and an exception
occurs in function C . If it is not handled in C , the exception passes to B and then to A .
If never handled, an error message is spit out and our program come to a sudden,
unexpected halt.
A critical operation which can raise exception is placed inside the try clause and the code that
handles exception is written in except clause.
It is up to us, what operations we perform once we have caught the exception. Here is a
simple example.
The entry is a
Oops! <class 'ValueError'> occured.
RECOMMENDED READINGS Next entry.
In this program, we loop until the user enters an integer that has a valid reciprocal. The
portion that can cause exception is placed inside try block.
If no exception occurs, except block is skipped and normal ow continues. But if any
exception occurs, it is caught by the except block.
Here, we print the name of the exception using ex_info() function inside sys module and
ask the user to try again. We can see that the values 'a' and '1.3' causes ValueError and '0'
causes ZeroDivisionError.
This is not a good programming practice as it will catch all exceptions and handle every case
in the same way. We can specify which exceptions an except clause will catch.
A try clause can have any number of except clause to handle them di erently but only one
will be executed in case an exception occurs.
We can use a tuple of values to specify multiple exceptions in an except clause. Here is an
example pseudo code.
1. try:
2. # do something
3. pass
4.
5. except ValueError:
6. # handle ValueError exception
7. pass
8.
9. except (TypeError, ZeroDivisionError):
10. # handle multiple exceptions
11. # TypeError and ZeroDivisionError
12. pass
13.
14. except:
15. # handle all other exceptions
16. pass
Raising Exceptions
In Python programming, exceptions are raised when corresponding errors occur at run time,
but we can forcefully raise it using the keyword raise.
We can also optionally pass in value to the exception to clarify why that exception was raised.
try...finally
The try statement in Python can have an optional finally clause. This clause is executed no
matter what, and is generally used to release external resources.
For example, we may be connected to a remote data center through the network or working
with a le or working with a Graphical User Interface (GUI).
In all these circumstances, we must clean up the resource once used, whether it was
successful or not. These actions (closing a le, GUI or disconnecting from network) are
performed in the nally clause to guarantee execution.
1. try:
2. f = open("test.txt",encoding = 'utf-8')
3. # perform file operations
4. finally:
5. f.close()
This type of construct makes sure the le is closed even if an exception occurs.
« PREVIOUS
PYTHON BUILT-IN EXCEPTIONS PYTHON USER-DEFINED EXCEPTION
NEXT
»
R Tutorials
Algorithms Tutorials