In this Page, We are Providing Python Programming – Exceptions. Students can visit for more Detail and Explanation of Python Handwritten Notes Pdf.
Python Programming – Exceptions
Exceptions
The exception is a way of breaking out of the normal flow of control of a code block in order to handle the error or other exceptional conditions. An exception is raised at the point where the error is detected.
>>> while True print ' Hello world ' SyntaxError: invalid syntax >>> 10 / 0 Traceback (most recent call last) : File "<pyshell#l>", line 1, in <module> 10 / 0 ZeroDivisionError: integer division or modulo by zero >>> 4+tt*3 Traceback (most recent call last) : File "<pyshe11#2>", line 1, in <module> 4+tt*3 NameError: name ' tt ' is not defined >>> ' 5 '+7 Traceback (most recent call last) : File "<pyshe11#3>", line 1, in <module> ' 5 '+7 TypeError: cannot concatenate ' str ' and ' int ' objects
The last line of the error message indicates what went wrong. Exceptions are of different types, and the type is printed as part of the message; the types in the above example are SyntaxError, ZeroDivisionError, NameError, and TypeError. Standard exception names are built-in identifiers (not reserved keywords). The rest of the lines provides detail based on the type of exception and what caused it.
- Python Programming – Constants
- Python Data Persistence – Exceptions
- Python Programming – Simple statement
Handling exceptions
If there is some suspicious code that may raise an exception, it can be handled by placing the suspicious code in a try compound statement. After the try clause, include an except clause, followed by a block of code that handles the problem. The following example attempts to open a file and write something in the file.
# ! / usr / bin / python try : fh = open ( " testflie " , " w " ) fh.write ( " This is my test file for exception handling ! ! " ) except IOError : print " Error: can\'t find the file or read data " else: print " Written content in the file successfully " fh.close ( )
Here are few important points that need to be remembered:
- A single try statement can have multiple except clauses. This is useful when the try clause contains statements that may throw different types of exceptions.
- A generic except clause can be provided, which handles any exception.
- After the except clause(s), and else clause can be included. The code in the else clause is executed, if the code in the try clause does not raise an exception.