Python Error: Try, Except and RaiseHandle errors: use the try, except and raise keywords. Use finally to always run code.
Error.In an earthquake great damage is seen. Destruction is everywhere. In computer programs, errors can occur at any level—the machine, the software.
In a Python programwe deal with problems with files, modules and bad logic. We use try, except and raise statements. We handle errors.
This simple program.It introduces a block that follows the try statement. The division expression has zero as the denominator, causing a ZeroDivisionError.
Except: In the except statement, we receive the ZeroDivisionError. And we print a special message.
Note: This program does not terminate because of this exception. We could continue the program after this point.
|Python program that uses except statement try: x = 1 / 0 except ZeroDivisionError: print("Tried to divide by zero") Output Tried to divide by zero|
Raise.We create exceptions in our code with raise. This program uses the Exception type. The mistake() method creates a custom string based on its parameter. It then raises an exception.
Traceback: The Python environment helpfully shows a traceback. This contains the methods called. The mistake() call is shown.
|Python program that uses raise def mistake(name): # Raise an example with custom string. raise Exception(name + " caused exception") # Call method. mistake("Voorheesville") Output Traceback (most recent call last): File "C:\file.py", line 4, in <module> mistake("Voorheesville") File "C:\file.py", line 2, in mistake raise Exception(name + " caused exception") Exception: Voorheesville caused exception|
Reraise.An exception continues bubbling to the calling methods unless handled. In an except clause, we can use a "raise" statement with no argument. This reraises the exception.
Here: The "raise" statement the exception not to be captured. The print-statement is executed before the program terminates.
|Python program that reraises exception try: # This causes an exception. f = open("abc") except: print("Except hit") # Raise the exception again. raise Output Except hit Traceback (most recent call last): File "C:\programs\file.py", line 6, in <module> f = open("abc") IOError: [Errno 2] No such file or directory: 'abc'|
Else.The else-statement can be used after a try-except block. If no exception is thrown, the else-statements are executed. The else must come after the excepts.
Tip: In the else, you can perform an action required when no errors are encountered.
Here: We show a while-True infinite loop. We accept input from the console, and parse it with the int() built-in method.Convert: Int, String
Then: We attempt to divide by the number entered. If zero is entered, the except-block is reached. Otherwise, the else is reached.
|Python program that uses try, else while True: # Read int from console. denominator = int(input()) # Use int as denominator. try: i = 1 / denominator except: print("Error") else: print("OK") Output 1 OK 2 OK 0 Error|
Finally.This clause is always executed, even if an error is raised. We can use "finally" statements as a way to clean up, or ensure completion of tasks.
Here: An error is raised in the try clause. After the "except" clause is executed, the finally clause runs.
|Python program that uses finally try: # An error occurs. x = 1 / 0 except: # Except clause: print("Error encountered") finally: # Finally clause: print("Finally clause reached") Output Error encountered Finally clause reached|
As-keyword.We can name a variable within an except statement. We use the as-keyword for this. Here we name the IOError "err" and can use it within the clause.
|Python program that uses as, except try: f = open("does-not-exist") except IOError as err: # We can use IOError as an instance. print("Error:", err) print("Number:", err.errno) Output Error: [Errno 2] No such file or directory: 'does-not-exist' Number: 2|
Assert.With assert() we cause an AssertionError when a condition is not true. So we "assert" that conditions are valid as the program runs. These statements can be optimized out.assert
Traceback.When a program crashes, a stack trace (a list of the calling methods) is helpful for debugging. In Python this is called a Traceback. It is a call stack.
Here: The "outer" method causes a terrifying ZeroDivisionError. We see the inner() method too in the Traceback.
Lines: The Traceback helpfully provides line numbers to aid in our debugging efforts.
|Python program that shows traceback output def outer(n): return 100 / n def inner(n): return outer(n) # This causes an error. # ... Python provides a stack trace that shows the call stack. inner(0) Output Traceback (most recent call last): File "C:\programs\file.py", line 12, in <module> inner(0) File "C:\programs\file.py", line 8, in inner return outer(n) File "C:\programs\file.py", line 5, in outer return 100 / n ZeroDivisionError: division by zero|
Errors.Many specific errors occur in Python programs. Even aspects of a program such as its indentation leads to errors. Other problems, such as invalid method calls, also provoke trouble.AssertionErrorIndentationErrorIOErrorKeyErrorNameError: ImportSyntaxError
Performance analysis.This is important—it helps us develop more efficient programs in the first place. But first, we must benchmark small programs to determine the speed of constructs.
Here: This program causes a ZeroDivisionError. It compares that loop to a version that tests against zero with an if-statement.If
|Python program that times exceptions import time print(time.time()) # Version that causes exception. v = 0 i = 0 while i < 10000000: try: x = 10 / v except ZeroDivisionError: x = 0 i += 1 print(time.time()) # Version that uses if-check. v = 0 i = 0 while i < 10000000: if v != 0: x = 10 / v else: x = 0 i += 1 print(time.time()) Output 1346178493.989 1346178499.7 (Version 1 = 5.711 s) 1346178501.788 (Version 2 = 2.088 s)|
Our result.The loop body that uses exception-handling is more than twice as slow. The exception is actually raised on each iteration through the loop.While
Tip: Avoiding exceptions, as by checking a denominator against zero, often leads to performance advantages.
Exception handlingintroduces an alternative control flow. When an exception is raised, control shifts to the except statement. It does not return to where it left.
A note.Exceptions provide a cleaner, simpler way to handle certain types of errors. They streamline programs. They eliminate the burden of excessive error checks in important logic.
Dot Net Perls
|© 2007-2019 Sam Allen. All rights reserved. Written by Sam Allen, email@example.com.|