
- Python Basic Tutorial
- Python - Home
- Python - Overview
- Python - Environment Setup
- Python - Basic Syntax
- Python - Comments
- Python - Variables
- Python - Data Types
- Python - Operators
- Python - Decision Making
- Python - Loops
- Python - Numbers
- Python - Strings
- Python - Lists
- Python - Tuples
- Python - Dictionary
- Python - Date & Time
- Python - Functions
- Python - Modules
- Python - Files I/O
- Python - Exceptions
How to use the try-finally clause to handle exception in Python?
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.
One very important point is that we can either define an “except” or a “finally” clause with every try block. You can’t club these together. Also, you shouldn’t use the “else” clause along with a “finally” clause.
Example
Given code can be rewritten as follows
try: foo = open ( 'test.txt', 'w' ) foo.write ( "It's a test file to verify try-finally in exception handling!!") print 'try block executed' finally: foo.close () print 'finally block executed'
Output
try block executed finally block executed
- Related Articles
- The try-finally Clause in Python
- How to handle an exception in Python?
- How to handle Python exception in Threads?
- How to use Grouping clause to handle NULLS in Oracle?
- How do you handle an exception thrown by an except clause in Python?
- How do we use try...catch...finally statement in JavaScript?
- How to handle python exception inside if statement?
- How to handle exception inside a Python for loop?
- How to handle a python exception within a loop?
- How to handle the Runtime Exception in Java?
- Explain try, except and finally statements in Python.
- How to handle an exception in JSP?
- Try-Catch-Finally in C#
- How to handle the exception using UncaughtExceptionHandler in Java?
- What is the best way to handle list empty exception in Python?

Advertisements