when programming in Python, you often see some error messages. Python has two kinds of errors that are easy to identify: syntax errors and exceptions. Python uses special objects called exceptions to manage errors that occur during program execution. Whenever an error occurs that confuses python, it creates an exception object. If you write code to handle the exception, the program will continue to run; If you do not handle the exception, the program will stop and display a traceback with a report about the exception. Exceptions are handled using the try exception code block. The try except code block lets Python perform the specified operation and tells Python what to do when an exception occurs. When the try except code block is used, the program will continue to run even if an exception occurs.
syntax error
Python syntax errors or parsing errors are often encountered by beginners, as shown in the following examples:
# input while True print("Hello world") # output Invalid syntax
the parser points out the wrong line and marks it where the error is found first.
abnormal
even if the syntax of a Python program is correct, errors may occur when running it. Errors detected during runtime are called exceptions. Most exceptions are not handled by the program and are displayed in the form of error messages. Exceptions appear in different types, which are printed as part of the information. The front part of the error message shows the context in which the exception occurred, and displays the specific information in the form of call stack.
# input str1 = 2 + "3" print(str1) # output Traceback (most recent call last): File "C:/script/error.py", line 1, in <module> str1 = 2 + "3" TypeError: unsupported operand type(s) for +: 'int' and 'str'
exception handling
try/except statement
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 exception 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 exception type matches the name after exception, the corresponding exception clause will be executed.
if an exception does not match any except, the exception will be passed to the upper try.
a try statement may contain multiple except clauses to handle different specific exceptions. At most one branch will be executed. The handler will only handle exceptions in the corresponding try clause, not exceptions in other try handlers.
# input try: print(5/0) except ZeroDivisionError: print("You can't divide by zero!") # output You can't divide by zero!
try/except... else statement
the try/except statement also has an optional else clause. If this clause is used, it must be placed after all except clauses. The else clause will be executed when no exception occurs in the try clause.
# input try: print(0/5) except ZeroDivisionError: print("You can't divide by zero!") else: print("Go ahead") # output 0.0 Go ahead
using else clause is better than putting all statements in try clause, which can avoid some unexpected exceptions that exception can't catch. Exception handling does not only deal with exceptions that happen directly in the try clause, but also handles exceptions thrown in functions that are called in the clause (or even indirectly called functions).
# input def fail(): x = 5/0 try: fail() except ZeroDivisionError: print("You can't divide by zero!") else: print("Go ahead") # output You can't divide by zero!
try finally statement
try finally statement will execute the last code whether an exception occurs or not.
# input def fail(): x = 5/0 try: fail() except ZeroDivisionError: print("You can't divide by zero!") else: print("Go ahead") finally: print("Well done") # output You can't divide by zero! Well done
exception thrown
Python throws a specified Exception using the raise statement. The raise syntax format is as follows. The only argument to raise 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 whether an Exception is thrown and don't want to deal with it, a simple raise statement can throw it again.
raise [Exception [, args [, traceback]]]
# input x = 10 if x > 5: raise Exception('x Cannot be greater than 5. x The value of is: {}'.format(x)) # output Traceback (most recent call last): File "C:/script/error.py", line 16, in <module> raise Exception('x Cannot be greater than 5. x The value of is: {}'.format(x)) Exception: x Cannot be greater than 5. x The value of is: 10
user defined exception
you can have your own exceptions by creating a new Exception class. The Exception class inherits from the Exception class and can inherit directly or indirectly. When creating a module may throw many different exceptions, a common approach is to create a basic Exception class for the package, and then create different subclasses for different error conditions based on the basic class.
# input 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) # output My exception occurred, value: 4