home PYTHONJAVA
 

Python3 errors and exceptions

As a Python beginner, when you first learn Python programming, you will often see some error messages. We didn't mention them in the previous section. We will introduce them in this chapter.

Python has two types of errors that are easy to identify: syntax errors and exceptions.

Syntax error

Python's syntax errors, or parsing errors, are common to beginners, as in the following examples

>>>while True print< /span>('Hello world< Span class="hl-quotes">') File "< Span class="hl-string"><stdin>", line 1, in ? while True print('Hello world')< /span> ^ SyntaxError: invalid< Span class="hl-code"> syntax

In this example, the function print() is checked for errors, which is missing a colon (:) in front of it.

The parser pointed out the line that was in error and marked a small arrow at the location of the error found first.

Exception

Even if the syntax of the Python program is correct, an error may occur while running it. Errors detected during runtime are called exceptions.

Most exceptions are not handled by the program and are presented here as error messages:

>>>10 * (1 /0) Traceback (most recent call last ): File "< Span class="hl-string"><stdin>", line 1, in ? ZeroDivisionError: division< Span class="hl-code"> by zero >>> 4 + Spam*3 Traceback (most recent call last ): File "< Span class="hl-string"><stdin>", line 1, in ? NameError: name< Span class="hl-code"> 'spam' is not defined >>> '2 ' + 2 Traceback (most recent call last ): File "< Span class="hl-string"><stdin>", line 1, in ? TypeError: Can< Span class="hl-quotes">'t convert 'int' object to str implicitly

Exceptions appear in different types, and these types are printed as part of the information: The types in the examples are ZeroDivisionError, NameError, and TypeError.

The front part of the error message shows the context in which the exception occurred and displays the specific information in the form of a call stack.

Exception handling

In the following example, let the user enter a valid integer, but allow the user to interrupt the program (using Control-C or the method provided by the operating system). User interrupted messages will raise a KeyboardInterrupt 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 statement between the keyword try and the keyword except)
  • If no exception occurs, the except clause is ignored and the try clause ends after execution.
  • If an exception occurs during the execution of the try clause, the rest of the try clause will be ignored. If the type of the exception matches the name after except, the corresponding except clause will be executed. Finally execute the code after the try statement.
  • If an exception does not match any except, then the exception will be passed to the upper try.

A try statement may contain multiple except clauses to handle different specific exceptions. At most only one branch will be executed.

The

handler will only handle exceptions in the corresponding try clause, not exceptions in other try handlers.

An exception clause can handle multiple exceptions at the same time. These exceptions will be placed in parentheses as a tuple, for example:

except ( RuntimeError, TypeError< Span class="hl-code">, NameError): pass

The last except clause can ignore the name of the exception and it will be used as a wildcard. You can use this method to print an error message and then throw the exception again.

import sys try: f= open< Span class="hl-brackets">('myfile.txt') s= f< Span class="hl-code">.readline() i= int< Span class="hl-brackets">(s.strip()) except OSError as err: print(" OS error: {0}".format(err)) except ValueError: print(" Could not convert data to an integer.")< /span> except: print(" Unexpected error:", sys.exc_info()[0< /span>]) raise
The

try except statement also has an optional else clause. If you use this clause, you must put it after all the except clauses. This clause will be executed when there is no exception in the try clause. E.g:

for arg in sys.argv[1:]: try: f = open(arg, 'r') except IOError: print('cannot open', arg) else: print(arg, 'has', len(f.readlines()), 'lines') f.close()

It's better to use the else clause than to put all the statements in the try clause, so that you can avoid unexpected exceptions that are not caught by except.

Exception handling does not only deal with exceptions that occur directly in the try clause, but also handles exceptions thrown in functions called in clauses (or even indirectly called functions). For example:

>>>def this_fails() : x= 1< Span class="hl-code">/0 >>> try: this_fails()< Span class="hl-code"> except ZeroDivisionError as err: print('< Span class="hl-string">Handling run-time error:', < Span class="hl-identifier">err) Handling run-time error: int division or modulo by zero

Throw an exception

Python uses the raise statement to throw a specified exception. For example:

>>>raise NameError('HiThere') Traceback (most recent call last): File "<stdin>", line 1, in ? NameError: HiThere

raise The only parameter that specifies the exception to be thrown. It must be an exception instance or an exception class (that is, a subclass of Exception ).

If you just want to know if this throws an exception and doesn't want to handle it, then a simple raise statement can throw it again.

>>>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

User-defined exception

You can have your own exception by creating a new exception class. Exception classes inherit from the Exception class and can be inherited directly or indirectly, 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!'

The names of most exceptions end with "Error", just like the standard exception name.


Define cleanup behavior

The

try statement has an optional clause that defines the cleanup behavior that will be performed under any circumstances. For example:

>>>try: ... raise KeyboardInterrupt ... finally: ... print('Goodbye, world!') ... Goodbye, world< Span class="hl-code">! Traceback (most recent call last ): File "< Span class="hl-string"><stdin>", line 2, in <module< /span>> KeyboardInterrupt

The above example will execute regardless of whether there is an exception in the try clause.

If an exception is thrown in the try clause (or in the except and else clauses) without any exception intercepting it, then the exception will be thrown again after the finally clause is executed. .

The following is a more complicated example (with the except and finally clauses in the same try statement):

>>>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.0 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'

Predefined cleanup behavior

Some objects define standard cleanup behavior, regardless of whether the system successfully used it, and once it is not needed, then this standard cleanup behavior will be performed.

This example shows trying to open a file and then print the content to the screen:

for line in open("myfile.txt"): print(line, end="")

The problem with this code is that when the execution is complete, the file will remain open and not closed.

The keyword with statement ensures that objects such as files will correctly execute their cleanup methods after they are used:

with open ("myfile.txt") as f: for line in f: print(line< Span class="hl-code">, end="")

After the above code is executed, even if there is a problem during processing, the file f will always be closed.






welookups is optimized for learning.© welookups. 2018 - 2019 All Right Reserved and you agree to have read and accepted our term and condition.