Chapter1 - Exception Handling
Chapter1 - Exception Handling
Handling
Introduction:
While executing a python program, sometimes the program does not execute
at all or the program executes but generates unexpected output or behaves
abnormally. These occur because of the syntax errors, logical errors or
runtime errors in the code. In Python, exceptions are triggered automatically.
However, exceptions can be forcefully triggered and handled through program
code.
Syntax errors:
• It occurs when the rules of a particular programming language is not
followed.
• It is also called as parsing errors.
• When a syntax error is encountered, the interpreter does not execute until
the errors are rectified, saved and the program is rerun.
Exceptions:
Python provides many types of exceptions thrown in various situations. Let's take
a look at the most common built-in exceptions with their examples:
NameError – Raised when a name doesn't exist among either local or global
variables:
•TypeError – Raised when an operation is run on an inapplicable data type:
If required, we can also define our own exceptions in Python called Python User-defined
Exceptions or custom exceptions.
We can handle these built-in and user-defined exceptions in Python
using try, except and finally statements.
The try...except block is used to handle exceptions in Python. Here's the syntax of try...except block:
try:
# code that may cause exception
except:
# code to run when exception occurs
Here, we have placed the code that might generate an exception inside the try block. Every try
block is followed by an except block.
When an exception occurs, it is caught by the except block. The except block cannot be used
without the try block.
In the example, we are trying to divide a number by 0. Here, this code generates an exception.
To handle the exception, we have put the code, result = numerator/denominator inside the try block.
Now when an exception occurs, the rest of the code inside the try block is skipped.
The except block catches the exception and statements inside the except block are executed.
If none of the statements in the try block generates an exception, the except block is skipped.
Output
Error: Denominator cannot be 0. This is finally block.
In the above example, we are dividing a number by 0 inside the try block. Here, this code generates an exception.
The exception is caught by the except block. And, then the finally block is executed.
Raising Exceptions:
Each time an error is detected in a program, the python interpreter raises an exception.
Exception handlers gets executed when a specific exception is raised.
Programmers can also forcefully raise exceptions in a program using “raise” and “assert”
statements.Once an exception is raised, no further statement in the current block of code is
executed.Raising an exception involves interrupting the normal flow of execution of the
program and jumping to that part of the program which is written to handle such
exceptional situations.
The raise statement:
The raise statement can be used to throw an exception.
The syntax of raise statement is:
raise exception-name[(optional argument)]
The argument is generally a string that is displayed when the exception is raised.
Example:
Raise an error and stop the program if x is lower than 0:
x = -1
if x < 0:
raise Exception("Sorry, no numbers below zero")
The assert statement:
An assert statement in Python is used to test an expression in the program code. It is merely a Boolean expression that
has a condition or expression checks if the condition returns true or false. If it is true, the program does not do
anything, and it moves to the next line of code. But if it is false, it raises an AssertionError exception with an optional
error message.
This example shows the working of assert with the error message.
def avg(scores):
assert len(scores) != 0,"The List is empty."
return sum(scores)/len(scores) Explanation: In the above example, we have passed a non-
empty list scores2 and an empty list scores1 to
scores2 = [67,59,86,75,92] the avg() function. We received an output for scores2 list
print("The Average of scores2:",avg(scores2)) successfully, but after that, we got an error AssertionError: List
is empty. The assert condition is satisfied by the scores2 list
scores1 = [] and lets the program continue to run.
print("The Average of scores1:",avg(scores1)) However, scores1 doesn't satisfy the condition and gives an
AssertionError.
Output:
Output
If we pass an odd number:
Enter a number: 1
Not an even number!
If we pass an even number, the reciprocal is computed and displayed.
Enter a number: 4
0.25
However, if we pass 0, we get ZeroDivisionError as the code block inside else is not handled by preceding
except.
Enter a number: 0
Traceback (most recent call last):
File "<string>", line 7, in <module>
reciprocal = 1/num
ZeroDivisionError: division by zero
Here, the assert statement in the code checks that num is an even number; if num is odd, it raises an
AssertionError, triggering the except block.
Note: Exceptions in the else clause are not handled by the preceding except clauses.
Python try...finally
In Python, the finally block is always executed no matter whether there is an exception or not.
The finally block is optional. And, for each try block, there can be only one finally block.
try:
numerator = 10
denominator = 0
result = numerator/denominator
print(result)
except:
print("Error: Denominator cannot be 0.")
finally:
print("This is finally block.")
Output
Error: Denominator cannot be 0.
This is finally block.
In the above example, we are dividing a number by 0 inside the try block. Here, this code
generates an exception.
The exception is caught by the except block. And, then the finally block is executed.