Python

Exception handling in Python

1 CATCHING EXCEPTION

Bất cứ khi nào một lỗi runtime xảy ra, nó sẽ tạo một exception object. Chương trình sẽ dừng lại tại nơi xảy ra lỗi và Python sẽ in ra một đoạn message mô tả về lỗi đã xảy ra. Error message format: type of error: specifics about the error.

Sometimes we want to execute an operation that might cause an exception, but we don’t want the program to stop. We can handle the exception using the try statement to “wrap” a region of code.

Try statement has 4 clauses, try … except … else … finally

The try clause executes and monitors the statements in the first block, if no exceptions occur, it skips the block under the except clause; if any exception occurs, it executes the statements in the except clause and then continues.

The else clauses that run if no exception occurs during the try suite. The use of the else clause is better than adding additional code to the try clause because it avoids accidentally catching an exception that wasn’t raised by the code being protected by the try … except statement.

The finally clauses that run whether an exception happens or not.

Example 1:

filename = input('Enter a file name: ')
try:
    f = open(filename, 'r')
except:
    print('There is no file named ', filename)

In example 1, except clause will catch all exceptions.

A try statement may have more than one except clause, to specify handlers for different exceptions. At most one handler will be executed. An except clause may name multiple exceptions as a parenthesized tuple, see Table 1.

clauseformat

Table 1 – try statement clause formats

In except clauses, type is an expression giving the exception class to be caught, and an extra variable name value can be used to intercept the instance of the exception class that was raised.

Type of error bao gồm: superclasses (BaseException, Exception, BufferError, ArithmeticError, LookupError và OSError) và specific exceptions (NameError, ValueError, TypeError, MemoryError, ZeroDivisionError…). Specific exceptions được dùng cho các exception cụ thể, còn superclasses cho trường hợp tổng quát, thường dùng nhất là Exception.

Example 2:

try:
    number = int(input())
except Exception as e:
    print(e)

Input: a
Output: invalid literal for int() with base 10: ‘a’

Example 3:

while True:
    try:
        number = int(input())
        print(100/number)
    except ValueError as e:
        print('You must enter a number!')
    except ZeroDivisionError as e:
        print('Divide by zero!')
    else:
        print('Finished!')
        break

Input: d
Output: You must enter a number!

Input: 0
Output: Divide by zero!

Input: 50
Output: 2
Output: Finished!

2 RAISING EXCEPTION

Exceptions can be raised automatically by Python, or explicitly by code in raise statements. So if your program detects an error condition, you can raise an exception.

Example 4:

def get_age():
    try:
        age = int(input('Please enter your age: '))
        if age < 0:
            raise ValueError('{0} is not a valid age.'.format(age))
    except Exception as e:
        print(e)
    else:
        return age

Input: d
Output: invalid literal for int() with base 10: ‘d’

Input: 5
Output: 5

Input: -10
Output: -10 is not a valid age.

3 FINALLY CLAUSE

A finally clause is always executed before leaving the try statement, whether an exception has occurred or not. When an exception has occurred in the try clause and has not been handled by an except clause (or it has occurred in an except or else clause), it is re-raised after the finally clause has been executed. The finally clause is also executed “on the way out” when any other clause of the try statement is left via a break, continue or return statement.

Example 5:

while True:
    try:
        number = int(input('enter a number: '))
        if number < 0:
            break
    except Exception as e:
        print(e)
    else:
        print(number)
    finally:
        print('Thank you!')

Input: b
Output: invalid literal for int() with base 10: ‘b’
Output: Thank you!

Input: 5
Output: 5
Output: Thank you!

Input: -10
Output: Thank you!

Không giống với finally clause, else clause không được thực thi khi trước nó có break, continue hoặc return.

Reference:
[1] Errors and Exceptions.
[2] Learning with Python 3.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s