>>> 10 * (1/0) #ZeroDivisionError: integer division or modulo by zero
>>> 4 + spam*3 #NameError: name 'spam' is not declared
>>> '2' + 2 #TypeError: cannot concatenate 'str' and 'int' objects
Here ZeroDivisionError, NameError and TypeError are name of the built-in exception that occurred.Standard exception names are built-in identifiers (not reserved keywords).
1. In Python, exceptions (also known as errors) are objects that are raised (or thrown) by
code that encounters an unexpected circumstance.
2. A raised error may be caught by a surrounding context that “handles” the exception in an appropriate fashion.
3. If Exception occurs and If uncaught, an exception causes the interpreter
to stop executing the program.
Following are list of common exception class found in python:(Image from DSA by Goodrich)
|Common exception classes in Python|
Enter valid input --> # ctrl+c is pressed
Operation cancelled .
Enter valid input --> test_input
You entered test_input
1. Normal operational code lines are placed inside try block, as in above example valid user input is
expected in try block. i.e : Watch for exception in try block.
2. Once exception occurs corresponding except block gets executed.
3. with one try block there can be N number of except block and there has to be at least one except
clause associated with every try clause.
4. We can also have an optional else clause associated with a try..except block. The else clause is executed if no exception occurs.
5. If an exception is not caught within the body of the function, the execution of the function
immediately ceases and the exception is propagated to the calling context.
Exception raising in python is carried out using raise statement with an appropriate instance
of an exception class as an argument. i.e: The error or exception that you can raise should be a class which directly or indirectly must be a derived class of the Exception class. Consider an example to understand how we can raise an exception. Find square root of an number and raise an exception when user input is negative(Square root of a negative number is imaginary value).
Open Python IDLE. Create a new file and copy following codes.
Enter number: 25
Sqaure root of number is 5.000000
Enter number: -25
ValueError type caught, Input is negative!!
Lets walk through sample output: When input is 25 , square root 5.00000 is printed and when input is negative number : -25, then ValueError exception is raised and caught in calling context.
Python support user defined exception.Exceptions should typically be derived from the Exception class, either directly or indirectly. Click here to know how to create user defined exception.
Clean-up actions in python is achieved using try...finally. A finally clause is always executed before leaving the try statement, whether an exception has occurred or not.When an exception has occurred in the try clause and has not been handled by an except clause (or it has occurred in a except or else clause), it is re-raised after the finally clause has been executed. Let's write a sample code to understand use of finally with try statement.Sample output: On executing divide(12,0 ), finally block is executed after exception ZeroDivisionError is caught.
division by zero!
executing finally clause
While when divide("12","2" ) is executed, finally block is executed before the exception is re-raised and thrown on console.
executing finally clause
Traceback (most recent call last):
File "C:/Python27/clean_finally.py", line 11, in <module>
File "C:/Python27/clean_finally.py", line 3, in divide1
result = x / y
TypeError: unsupported operand type(s) for /: 'str' and 'str'
Predefined Clean-up Actions in python is done using with statement. With statement guarantee that resources are closed and placed in pool right after its use, even if execution is failed.In the following code lines, after the statement is executed, the file f is always closed, even if a problem was encountered while processing the lines.
Previous:Python input and output Next:Iterators and Generators