Sunday, February 12, 2017

Exceptions Handling

To handle exceptions, and to call code when an exception occurs, you can use try/except statement. The try block contains code that might throw an exceptions. If that exception occurs, the code in the try block stops being executed, and the code in the except block is run. If no error occurs, the code in the except doesn’t run.
try:
    a = 7
    b = 0
    print(a/b)
    print('Done calculation')
except ZeroDivisionError:
    print('An error occured due to the zero division')
An error occured due to the zero division

In the code above, the except statement defines the type of exception to handle (in our case, the ZeroDivisonError). We can expand this example with the raw_input function in order to input numbers we want.
userinput1 = raw_input('Enter first value: ')
userinput2 = raw_input('Enter second value: ')
try:
    a = int(userinput1)
    b = int(userinput2)
    print(a/b)
    print('Done calculation')
except ZeroDivisionError:
    print('An error occured due to the zero division')
except ValueError:
    print("You've entered a non-integer value.")
First run:
Enter first value: kill

Enter second value: bill
You've entered a non-integer value.

Second run:
Enter first value: 5

Enter second value: 6
0
Done calculation


Example: What is the output of this code ?
try:
    variable = 10
    print(10/2)
except ZeroDivisionError:
    print('Error')
print('Finished')
5
Finished

A try statement can have multiple different except blocks to handle different exceptions. Multiple exceptions can also be put into a single except block using parenthesis, to have the except block handle all of them.
try:
    a = 10
    print a + 'Hello'
    print a/2
except ZeroDivisionError:
    print 'Divide by zero'
except (ValueError, TypeError):
    print 'Error occured'
Error occured

Example: What is the output of this code?
try:
    a = 30
    print a / 0
    print 'the meaning of life'
except(ValueError, TypeError):
    print 'ValueError or TypeError occured'
except ZeroDivisionError:
    print 'Divide by zero'
Divide by zero
An except statement without any exception specified will catch all errors. These should be used sparingly, as they can catch up unexpected errors and hid programming mistakes.
try:
    word = 'SPAM'
    print word/0
except:
    print 'An error occurred'
An error occurred

Exception handling is particularly useful when dealing with user input.
Example: fill in the blanks to handle all possible exceptions.
___:
    a = _____(':')
    b = input(':')
    print float(a)/_____(b)
_____:
    _____ 'Invalid input'
:5

:6
0.833333333333

To ensure that code runs no matter what errors occur, you can use a finally statement. The finally statement is placed is placed at the bottom of a try/except statement. Code within a finally statement always runs after execution of the code in the try, and possibility in the except blocks.
try:
    print 'Hello'
    print 1/0
except ZeroDivisionError:
    print 'Divided by zero'
finally:
    print 'This code will run no matter what'
Hello
Divided by zero
This code will run no matter what

Example: what is the output of this code?
try:
    print 1
except:
    print 2
finally:
    print 3
1
3

Code in a finally statement even runs if an uncaught exception occurs in one of the preceding blocks.
try:
    print 1
    print 10/0
except ZeroDivisionError:
    print unknown_var
finally:
    print 'This is executed last'
1
This is executed last
NameError: name 'unknown_var' is not defined
Example: Fill in the blanks to create a try/except/finally block.
__:
    print 1
______:
    print 2
________:
    print 42
1
42


No comments:

Post a Comment