Py19: Exception
An exception is an unplanned event that occurs during program execution that disrupts the normal flow of a program. Example of some unplanned event is lost connectivity, missing resources, invalid input, etc.
Introduction
Exception handling ensures program flow is not disrupted in case of an event that may cause exceptions.
For example, dividing a number by zero will cause an error. This may occur when the user enters 0 for the second input in the following program.
num1 = int(input("Enter an number1: "))
num2 = int(input("Enter an number2: "))
ans = num1/num2
print(ans)
Output
Enter an number1: 1 Enter an number2: 0 Traceback (most recent call last): File "<string>", line 4, in <module> ZeroDivisionError: division by zero >
try...except
try: # contains code that may raise exception except: # code that handles the exception
Codes in the try-block are executed first. If an exception occurs, the rest of the codes in the try-block is skipped and codes in except clause will be executed before ending the try-statement. When the code runs without exception, the except clause is skipped, and the try-statement completes.
try:
num1 = int(input("Enter an number1: "))
num2 = int(input("Enter an number2: "))
ans = num1/num2
print(ans)
except:
print("Cannot divide by zero")
Run 1 (exception occurred and handled)
Enter an number1: 1 Enter an number2: 0 Cannot divide by zero >
Run2 (no exception occurred)
Enter an number1: 2 Enter an number2: 4 0.5 >
Catching specific error
We can catch specific exceptions by indicating the exception type after the except keyword.
except ExceptionType: # code
Giving an alias to the error type, the error object can be used in code
except ExceptionType as aliasName: # code
Example
try:
num1 = int(input("Enter an number1: "))
num2 = int(input("Enter an number2: "))
ans = num1/num2
print(ans)
except ZeroDivisionError as err:
print(err)
Output</
Enter an number1: 1 Enter an number2: 0 division by zero >
Catching multiple errors
The try statement can have more than one except clause in it, where each except clause catches a specific error type.
The program above may raise a ValueError exception if invalid input is entered by the user.
Enter an number1: one Traceback (most recent call last): File "<string>", line 2, in <module> ValueError: invalid literal for int() with base 10: 'one' >
The following example shows how two exceptions (ZeroDivisionError and ValueError) are handled in a try statement.
try:
num1 = int(input("Enter an number1: "))
num2 = int(input("Enter an number2: "))
ans = num1/num2
print(ans)
except ZeroDivisionError as err:
print(err)
except ValueError as err:
print(err)
Run 1 (ZeroDivisionError occurred and handled)
Enter an number1: 1 Enter an number2: 0 division by zero >
Run 2 (ValueError occurred and handled)
Enter an number1: 2 Enter an number2: four invalid literal for int() with base 10: 'four' >
try...except...finally
The finally-clause executes either there is an exception occurred or there isn't. It contains code that must be executed like closing files or connections.
try: # contains code that may raise exception except: # code that handles the exception finally: # the finally code
For example, the following program has the finally-clause that finishes up the program execution by displaying the Finish message.
try:
num1 = int(input("Enter an number1: "))
num2 = int(input("Enter an number2: "))
ans = num1/num2
print("Answer: ",ans)
except ZeroDivisionError as err:
print(err)
except ValueError as err:
print(err)
finally:
print("Finish")
Run 1 (No exception occurred, finally executed)
Enter an number1: 1 Enter an number2: 2 Answer: 0.5 Finish >
Run 2 (ZeroDivisionError occurred, finally executed)
Enter an number: 1 Enter an number2: 0 division by zero Finish >
Comments
Post a Comment