Python Try Except Then Try Again
35. Errors and Exception Handling
By Bernd Klein. Concluding modified: xix Apr 2022.
Exception Handling
An exception is an error that happens during the execution of a plan. Exceptions are known to not-programmers equally instances that practise not adjust to a general dominion. The proper noun "exception" in information science has this meaning every bit well: It implies that the problem (the exception) doesn't occur frequently, i.e. the exception is the "exception to the rule". Exception treatment is a construct in some programming languages to handle or bargain with errors automatically. Many programming languages like C++, Objective-C, PHP, Java, Cerise, Python, and many others have built-in support for exception treatment.
Error handling is more often than not resolved past saving the country of execution at the moment the error occurred and interrupting the normal menstruation of the program to execute a special role or piece of code, which is known as the exception handler. Depending on the kind of error ("division by cypher", "file open error" and and so on) which had occurred, the fault handler can "fix" the problem and the programm tin exist continued afterwards with the previously saved data.
Exception Handling in Python
Exception handling in Python is very similar to Coffee. The code, which harbours the risk of an exception, is embedded in a try block. While in Java exceptions are caught by catch clauses, in Python we have statements introduced by an "except" keyword. It's possible to create "custom-made" exceptions: With the raise argument information technology'due south possible to force a specified exception to occur.
Let's expect at a simple case. Assuming nosotros desire to inquire the user to enter an integer number. If nosotros use a input(), the input will be a string, which we have to cast into an integer. If the input isn't a valid integer, we will generate (raise) a ValueError. We show this in the post-obit interactive session:
n = int ( input ( "Please enter a number: " ))
With the help of exception handling, we can write robust code for reading an integer from input:
while True : try : n = input ( "Please enter an integer: " ) n = int ( n ) break except ValueError : print ( "No valid integer! Please try again ..." ) print ( "Great, you successfully entered an integer!" )
Information technology's a loop, which breaks only if a valid integer has been given. The while loop is entered. The code within the try clause will be executed statement by statement. If no exception occurs during the execution, the execution volition attain the interruption statement and the while loop volition exist left. If an exception occurs, i.e. in the casting of n, the residue of the try cake will exist skipped and the except clause will exist executed. The raised error, in our case a ValueError, has to match one of the names after except. In our example just ane, i.e. "ValueError:". After having printed the text of the print statement, the execution does another loop. It starts with a new input().
We could turn the lawmaking above into a office, which tin be used to have a foolproof input.
def int_input ( prompt ): while True : try : age = int ( input ( prompt )) return historic period except ValueError as due east : impress ( "Not a proper integer! Try information technology again" )
Nosotros use this with our dog historic period example from the chapter Conditional Statements.
def dog2human_age ( dog_age ): human_age = - 1 if dog_age < 0 : human_age = - ane elif dog_age == 0 : human_age = 0 elif dog_age == one : human_age = xiv elif dog_age == 2 : human_age = 22 else : human_age = 22 + ( dog_age - 2 ) * v return human_age
age = int_input ( "Age of your domestic dog? " ) print ( "Historic period of the dog: " , dog2human_age ( historic period ))
OUTPUT:
Non a proper integer! Try it again Not a proper integer! Effort information technology over again Age of the dog: 37
Multiple Except Clauses
A endeavor statement may have more than ane except clause for different exceptions. Just at most one except clause will be executed.
Our adjacent example shows a try clause, in which we open up a file for reading, read a line from this file and catechumen this line into an integer. There are at least ii possible exceptions:
an IOError ValueError
Just in example we take an additional unnamed except clause for an unexpected error:
import sys effort : f = open ( 'integers.txt' ) s = f . readline () i = int ( s . strip ()) except IOError as east : errno , strerror = eastward . args impress ( "I/O error( {0} ): {ane} " . format ( errno , strerror )) # e can be printed straight without using .args: # print(e) except ValueError : print ( "No valid integer in line." ) except : impress ( "Unexpected error:" , sys . exc_info ()[ 0 ]) raise
OUTPUT:
I/O error(2): No such file or directory
The handling of the IOError in the previous instance is of special interest. The except clause for the IOError specifies a variable "eastward" subsequently the exception name (IOError). The variable "eastward" is bound to an exception example with the arguments stored in instance.args. If nosotros call the above script with a not-existing file, we become the message:
I/O mistake(2): No such file or directory
And if the file integers.txt is non readable, e.chiliad. if we don't have the permission to read it, we get the following message:
I/O fault(13): Permission denied
An except clause may name more than i exception in a tuple of mistake names, as we see in the following example:
try : f = open ( 'integers.txt' ) s = f . readline () i = int ( due south . strip ()) except ( IOError , ValueError ): print ( "An I/O fault or a ValueError occurred" ) except : print ( "An unexpected fault occurred" ) enhance
OUTPUT:
An I/O mistake or a ValueError occurred
Nosotros desire to demonstrate now, what happens, if we telephone call a function within a endeavor cake and if an exception occurs inside the function telephone call:
def f (): 10 = int ( "four" ) try : f () except ValueError equally eastward : print ( "got it :-) " , east ) print ( "Let's get on" )
OUTPUT:
got it :-) invalid literal for int() with base x: 'four' Let'southward get on
the role catches the exception.
We will extend our instance now then that the function will take hold of the exception directly:
def f (): try : 10 = int ( "iv" ) except ValueError every bit e : print ( "got it in the function :-) " , east ) attempt : f () except ValueError every bit e : print ( "got information technology :-) " , e ) print ( "Let'southward become on" )
OUTPUT:
got it in the office :-) invalid literal for int() with base of operations 10: 'iv' Allow's get on
As we have expected, the exception is defenseless inside the office and not in the callers exception:
Nosotros add now a "enhance", which generates the ValueError again, then that the exception volition be propagated to the caller:
def f (): try : x = int ( "four" ) except ValueError every bit e : impress ( "got it in the part :-) " , e ) heighten try : f () except ValueError as e : print ( "got information technology :-) " , due east ) print ( "Let'due south get on" )
OUTPUT:
got it in the office :-) invalid literal for int() with base 10: 'four' got information technology :-) invalid literal for int() with base ten: 'four' Let's go on
Alive Python training
Upcoming online Courses
Enrol here
Custom-made Exceptions
Information technology's possible to create Exceptions yourself:
raise SyntaxError ( "Distressing, my mistake!" )
OUTPUT:
Traceback (well-nigh contempo call last): File "C:\\Users\\melis\\Anaconda3\\lib\\site-packages\\IPython\\core\\interactiveshell.py", line 3326, in run_code exec(code_obj, self.user_global_ns, self.user_ns) File "<ipython-input-15-a5649918d59e>" , line 1 , in <module> heighten SyntaxError("Sorry, my error!") File "<string>" , line unknown SyntaxError : Sad, my fault!
The best or the Pythonic way to exercise this, consists in defining an exception form which inherits from the Exception class. You lot volition take to go through the chapter on Object Oriented Programming to fully sympathise the following case:
course MyException ( Exception ): pass heighten MyException ( "An exception doesn't always prove the dominion!" )
OUTPUT:
--------------------------------------------------------------------------- MyException Traceback (most contempo call last) <ipython-input-iii-d75bff75fe3a> in <module> two pass iii ----> iv raise MyException( "An exception doesn't always bear witness the rule!" ) MyException: An exception doesn't always bear witness the rule!
Clean-upwardly Actions (endeavor ... finally)
And then far the try statement had always been paired with except clauses. But at that place is another way to use information technology as well. The try statement can exist followed by a finally clause. Finally clauses are called clean-up or termination clauses, because they must be executed nether all circumstances, i.e. a "finally" clause is always executed regardless if an exception occurred in a endeavour cake or non. A simple case to demonstrate the finally clause:
try : x = float ( input ( "Your number: " )) inverse = 1.0 / x finally : print ( "There may or may not have been an exception." ) impress ( "The inverse: " , inverse )
OUTPUT:
Your number: 34 There may or may not accept been an exception. The inverse: 0.029411764705882353
Combining try, except and finally
"finally" and "except" can exist used together for the aforementioned attempt block, as it can be seen in the following Python example:
effort : ten = float ( input ( "Your number: " )) inverse = 1.0 / x except ValueError : print ( "Yous should have given either an int or a float" ) except ZeroDivisionError : print ( "Infinity" ) finally : impress ( "There may or may not accept been an exception." )
OUTPUT:
Your number: 23 In that location may or may not have been an exception.
else Clause
The try ... except statement has an optional else clause. An else block has to be positioned afterwards all the except clauses. An else clause volition be executed if the try clause doesn't heighten an exception.
The following example opens a file and reads in all the lines into a listing called "text":
import sys file_name = sys . argv [ 1 ] text = [] attempt : fh = open ( file_name , 'r' ) text = fh . readlines () fh . close () except IOError : print ( 'cannot open' , file_name ) if text : print ( text [ 100 ])
OUTPUT:
This example receives the file name via a command line statement. So brand certain that you lot call information technology properly: Permit's assume that y'all saved this programme equally "exception_test.py". In this example, y'all have to call it with
python exception_test.py integers.txt
If you lot don't desire this behaviour, merely change the line "file_name = sys.argv[1]" to "file_name = 'integers.txt'".
The previous example is virtually the same as:
import sys file_name = sys . argv [ 1 ] text = [] endeavor : fh = open ( file_name , 'r' ) except IOError : print ( 'cannot open' , file_name ) else : text = fh . readlines () fh . shut () if text : print ( text [ 100 ])
OUTPUT:
The principal difference is that in the commencement case, all statements of the try block tin can pb to the aforementioned error message "cannot open ...", which is incorrect, if fh.close() or fh.readlines() enhance an error.
Live Python grooming
Upcoming online Courses
Enrol here
Source: https://python-course.eu/python-tutorial/errors-and-exception-handling.php
Post a Comment for "Python Try Except Then Try Again"