Try, Except

 The last control statement we will look at is the try, except statement. This statement controls how a program will proceed when an error occurs. 


Syntax

try:

    do something

except:

    do something else when an error occurs


Example

try:

    answer = 12/0

except:

    print('you really think 12 would divide by 0?')


When this is run, it will display the message 'you really think 12 would divide by 0?'. This is because when the program tries to execute answer = 12/0 in the try block, an error occurs since a number cannot divide by zero. The remaining of the try block is ignored and the statement in the except block is printed instead.


We can also display more specific error messages depending on the type of error by specifying it after the except keyword.


Example

try:

    userinput1 = int(input('enter a number '))

    userinput2 = int(input('enter another number '))

    answer = userinput1/userinput2

    print('the answer is', answer)

    myFile = open('missing.txt', 'r')

except ValueError: print('you didn\'t enter a valid number')

except ZeroDivisionError: print('you can\'t divide by zero dingus')

except Exception as e:

    print('unknownerr: ', e)


Output

Below are different outputs for different user inputs.


enter a number h

you didn't enter a valid number

The reason is that the user entered a string which cannot be cast into an integer. This is a ValueError. Therefore, the message in the except ValueError statement is displayed.


enter a number 12

enter another number 0

you can't divide by zero dingus

The reason is that the user entered 0 as the second input. Since a number cannot be divided by zero, this is a ZeroDivisionError Therefore, the message in the except ZeroDivisionError statement is displayed.


enter a number 12

enter another number 3

the answer is 4.0

unknownerr:  [Errno 2] No such file or directory: 'missing.txt'

The reason is that the user enters acceptable numbers and the line print('the answer is', answer) is executed correctly. However, the next line myFile = open('missing.txt', 'r') brings an error as missing.txt is not found. Since this is neither a ValueError nor a ZeroDivisionError, the last except command is executed.


There are many types of errors that can be displayed in Python, such as the ValueError error and the ZeroDivisionError error. Others include IOError, KeyError, TypeError, etc.


Python also comes with pre-defined error messages for every type of error. We use the as keyword to display the message. The

except Exception as e:

    print('unknownerr: ', e)

statement is an example of using the pre-defined error message. It serves as a final attempt to catch any unanticipated errors.

No comments:

Post a Comment