Python Errors and Exceptions | Python 3 Exception Handling Tutorial For Beginners 2018. Here in this blog post Coding compiler sharing Python 3 Errors and Exceptions tutorial for beginners. You will learn about Python exception handling as well. This Python tutorial is for beginners and intermediate learners who are looking to master in Python programming. Experienced Python programmers also can refer this tutorial to brush-up their Python 3 programming skills. Let’s start learning Python 3.
Python Errors and Exceptions
There has been no further discussion of error messages so far, but you may have already encountered some of the examples you have experimented with. There are (at least) two kinds of errors in Python: syntax errors and exceptions ( syntax errors and exceptions ).
Python Errors and Exceptions Tutorial | |
1. Grammatical errors | 5. User-defined exceptions |
2. Exceptions | 6. Defining Cleanup Behavior |
3. Exception Handling | 7. Predefined Cleanup Behavior |
4. Throwing an exception | 8. Python Errors and Exceptions Conclusion |
Related Articles: Python Getting Started Guide | Introduction to Python
1. Grammatical errors
Grammatical errors, also known as parsing errors, are probably the most common complaints you have while learning Python:
>>> the while True Print ( 'the Hello world' )
? File "<stdin>", Line 1, in
the while True Print ( 'the Hello world')
^
SyntaxError: invalid syntax
The parser indicates the wrong line and displays a small “arrow” in front of where the error was detected. Error is indicated by the arrow in front of (or at least so detected) caused marked: in this example, the function print () was found to errors, because the less a colon in front of it ( ':'
). The error will output the file name and line number, so if you input from a script you know where to go to check for errors.
2. Exceptions
Even if a statement or expression is syntactically correct, it may throw an error when it tries to execute it. Run-time detected errors known as anomalies , and the program will not unconditional collapse: Soon, you will learn how to handle them in Python programs.
However, most of the exceptions are not processed by the program and will eventually produce an error message as shown here:
>>> 10 * ( 1 / 0 )
Traceback (most recent call last):
File "<stdin>" , line 1 , in ?
ZeroDivisionError : int division or modulo by zero
>>> 4 + spam * 3
Traceback (most recent Call last):
File "<stdin>" , line 1 , in ?
NameError : name 'spam' is not defined
>>> '2' + 2
Traceback (most recent call last):
File "<Stdin>" , line1 , in ?
TypeError : Can't convert 'int' object to str implicitly
The last line of the error message indicates what went wrong. Exceptions also have different types. Exception types are shown as part of the error message: The exceptions in the example are ZeroDivisionError , NameError , and TypeError . When an error message is printed, the type of the exception is displayed as an abnormal built-in name.
This is true for all built-in exceptions, but user-defined exceptions are not (although this is a very useful convention). The standard exception name is a built-in ID (no reserved keywords).
This part of the line is a detailed description of the type of exception, which means that its content depends on the type of exception.
The first half of the error message lists the location of the exception in a stack. The source code line is usually listed in the stack, however, the source code from the standard input is not displayed.
Related Article: Python Interpreter Tutorial
3. Exception Handling
It is feasible to program selected exceptions through programming. Look at the following example: It will always require user input until enter a valid integer, but allows the user to interrupt the program (using Control-C
or any method supported by the system).
Note: A user generated interrupt will raise a Keyboard Interrupt exception.
>>> while True :
... try :
... x = int ( input ( "Please enter a number: " ))
... break
... except ValueError :
... print ( "Oops! That was no Valid number. Try again..." )
...
The try statement works as follows.
-
First, execute the try clause ( the part between the try and except keywords).
-
If no exception occurs, the except clause is ignored after the try statement is executed.
-
If an exception occurs during the execution of the try clause, the rest of the clause is ignored.
If the exception matches the type of exception specified after the except keyword, the corresponding except clause is executed. Then continue with the code after the try statement.
-
If an exception occurs , there is no matching branch in the except clause, and it is passed to the previous try statement.
If you still can not find the corresponding final statement processing, it becomes a unhandled exception and execution stops with a message as shown.
A try statement may contain more than one except clauses that specify different handling of exceptions. At most only one branch will be executed. Exception handlers only handle exceptions that occur in the corresponding try clause.
In the same try statement, exceptions that occur in other clauses are not processed. An except clause can list multiple exception names in parentheses, for example:
... except ( RuntimeError , TypeError , NameError ):
... pass
The last except clause can omit the exception name for use as a wildcard. You need to use this method with caution because it will easily hide an actual program error!
You can use this method to print an error message and then re throw the exception (allowing the caller to handle this exception):
Import sys
Try :
f = open ( 'myfile.txt' )
s = f . readline ()
i = int ( s . strip ())
except OSError as err :
print ( "OS error: {0} " . format ( err ))
Except ValueError :
print ( "Could not convert data to an integer." )
except :
print ( "Unexpected error:" , SYS . exc_info () [ 0 ])
The raise
A try … except statement can have an else clause that can only appear after all except clauses. When the try statement does not throw an exception, some code needs to be executed and this clause can be used. E.g:
for Arg in SYS . the argv [ . 1 :]:
the try :
F = Open ( Arg , 'R & lt' )
the except IOError :
Print ( 'CAN Not Open' , Arg )
the else :
Print ( Arg , 'has' , len ( F . the readlines ()), 'Lines' )
F . Close ()
It is better to use the else clause than to append the code in the try clause, because this avoids try … except accidentally intercepting exceptions thrown by those code that are not protected by them.
When an exception occurs, it may have an associated value, as abnormal parameters exist. Whether this parameter exists or not, depends on the type of the exception.
You can also specify a variable for the except clause after the exception name (list). The variable is bound to an exception instance, it is stored in instance.args
a parameter.
For convenience, the exception instance defines __str__() so that the print parameters can be accessed directly without reference .args
. This practice is not encouraged.
Related Articles: Learn Python In One Day
Instead, it is better to pass an argument to the exception (if you pass multiple arguments, you can pass a tuple) and bind it to the message attribute. Once an exception occurs, it binds all the specified attributes before throwing it.
>>> try :
... raise Exception ( 'spam' , 'eggs' )
... except Exception as inst :
... print ( type ( inst )) # the exception instance
... print ( inst . args ) # arguments stored in .args
... print ( inst ) # __str__ allows args to be printed directly,
... # but may be overridden in exception subclasses
... x , y = inst . args # unpack args
... print ( 'x =' , x )
... print ( 'y =' , y )
...
<class 'Exception'>
('spam', 'eggs')
('spam', 'eggs')
x = spam
y = eggs
For those unhandled exceptions, if one of them has parameters, it will be printed as the last part of the exception information (“details”).
Exception handlers not only handle exceptions that occur immediately in the try clause, they also handle exceptions that occur inside functions called in those try clauses. E.g:
>>> def this_fails ():
... x = 1 / 0
...
>>> try :
... this_fails ()
... except ZeroDivisionError as err :
... print ( 'Handling run-time error: ' , err )
...
Handling run-time error: int division or modulo by zero
Related Article: Python For Machine Learning
4. Throwing an exception
The raise statement allows the programmer to force throw a specified exception. E.g:
>>> raise NameError ( 'HiThere' )
Traceback (most recent call last):
File "<stdin>" , line 1 , in ?
NameError : HiThere
The exception to be thrown is identified by the raise ‘s unique parameter. It must be an exception instance or an exception class (class inherited from Exception ).
If you need to specify whether an exception was thrown, but do not want to deal with it, the raise statement allows you to simply re-throw the exception:
>>> try :
... raise NameError ( 'HiThere' )
... except NameError :
... print ( 'An exception flew by!' )
... raise
...
An exception flew by!
Traceback (most recent Call last):
File "<stdin>" , line 2 , in ?
NameError : HiThere
5. User-defined exceptions
Programs may name their own exceptions by creating a new exception type (content type, see the Python class ). Exception classes should usually be derived directly or indirectly from the Exception class, for example:
>>> class MyError ( Exception ):
... def __init__ ( self , value ):
... self . value = value
... def __str__ ( self ):
... return repr ( self . value )
...
>>> try :
... raise MyError ( 2 * 2 )
... except MyError as e :
... print ( 'My exception occurred, value:' , e . value )
...
My exception occurred, value: 4
>>> raise MyError ( 'oops!' )
Traceback (most recent call last):
File "< Stdin>" , line 1 , in ?
__main__.MyError : 'oops!'
In this example, Exception’s default __init__() is overridden. The new way simply creates the value attribute. This replaces the original way to create args properties.
An exception class can define anything that can be defined in any other class, but generally it is only for the sake of simplicity that only a few attribute information is added to it, so that an exception handling handle can be extracted.
Related Article: Python Data Structures
If a newly created module needs to throw several different kinds of errors, a common practice is to define an exception base class for the module, and then derive the corresponding exception subclass for different types of errors:
Class Error ( Exception ):
"""Base class for exceptions in this module."""
pass
Class InputError ( Error ):
"""Exception raised for errors in the input.
Attributes:
expression -- input expression in which the error occurred
message -- explanation of the error
"""
Def __init__ ( self , expression , message ):
self . expression = expression
self . message = message
Class TransitionError ( Error ):
"""Raised when an operations attempts a state transition that's not
allowed.
Attributes:
previous -- state at beginning of transition
next -- attempted new state
message -- explanation of why the specific transition is not allowed
"""
Def __init__ ( self , previous , next , message ):
self . previous = previous
self . next = next
self . message = message
Similar to standard exceptions, most exceptions are named with an “Error”.
Many of the standard modules have their own exceptions defined to report possible errors in the functions they define.
Related Article: Python Modules
6. Defining Cleanup Behavior
The try statement has another optional clause that aims to define the functions that must be performed under any circumstances. E.g:
>>> try :
... raise KeyboardInterrupt
... finally :
... print ( 'Goodbye, world!' )
...
Goodbye, world!
KeyboardInterrupt
Traceback (most recent call last):
File "<stdin>" , Line 2 , in ?
The finally clause must be executed after the program leaves the try whether or not an exception occurs . When try occurs not statements except exception trapping (or it happens except or else clause), the finally clause is executed after it is re-thrown.
The try statement exits via the break , continue, or return statement will also execute the finally clause. The following is a more complicated example:
>>> def divide ( x , y ):
... try :
... result = x / y
... except ZeroDivisionError :
... print ( "division by zero!" )
... else :
... Print ( "result is" , result )
... finally :
... print ( "executing finally clause" )
...
>>> divide ( 2 , 1 )
result is 2
executing finally clause
>>> divide ( 2 , 0 )
division by zero!
executing finally clause
>>> divide ( "2" , "1" )
executing finally clause
Traceback (most recent call last):
File " <stdin>" , line 1 , in ?
File "<stdin>" , line 3 , in divide
TypeError : unsupported operand type(s) for /: 'str' and 'str'
As you can see, the finally clause executes under any circumstances. The TypeError is thrown when two strings are divided and is not caught by the except clause, so it is re-throwed after the finally clause is executed.
In a real-world application, the finally clause is used to free external resources (files or network connections, etc.) regardless of whether they are in use or not.
Related Article: Python Input and Output
7. Predefined Cleanup Behavior
Some objects define a standard cleanup behavior, which will work regardless of whether the object is successful or not. The following example attempts to open the file and print the content to the screen.
For line in open ( "myfile.txt" ):
print ( line )
The problem with this code is that the open file is not closed immediately after the code is executed. This is nothing in simple scripts, but large applications can be problematic. The with statement makes it possible to ensure that objects such as files can always be cleaned in a timely manner.
With open ( "myfile.txt" ) as f :
for line in f :
print ( line )
After the statement is executed, the file f will always be closed even if the error occurs when the data in the file is processed. Whether other objects provide predefined cleanup behaviors to view their documentation.
Related Articles:
Python Programming Interview Questions