Chapter1 - Exception Handling

You might also like

Download as pdf or txt
Download as pdf or txt
You are on page 1of 16

Chapter1 -Exception

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:

Even if a statement or expression is syntactically correct, there might arise an


error during its execution. For example, trying to open a file that does not exist,
division by zero and so on. Such type of errors might disrupt the normal
execution of the program and are called exceptions.

An exception is a Python object that represents an error. When an error occurs


during the execution of a program, an exception is said to have been raised.
Such exceptions need to be handled, so that the program does not terminate
abnormally. It is important to catch and handle exceptions. For example,
provide an alternative version of the code execution when the given exception
occurs.
Built-In-Exceptions:
Commonly occurring exceptions are usually defined in the compiler/interpreter.
These are called built-in 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:

•ValueError – Raised when an operation or function takes in an invalid value of an argument:


•IndexError – Raised when an index doesn't exist in an iterable:

•IndentationError – Raised when indentation is incorrect:


•ZeroDivisionError – Raised at attempt to divide a number by zero:

•ImportError – Raised when an import statement is incorrect:


IOError: It is raised when the file specified in a program statement cannot be opened.
KeyboardInterrupt – It is raised when the user accidentally hits the Delete or Esc key
while executing a program due to which the normal flow of the program is interrupted.
EOFError – It is raised when the end of file condition is reached without reading any data
by input().
AssertionError - Raised when an assert statement fails.
FloatingPointError -Raised when a floating point operation fails.
KeyError - Raised when a key is not found in a dictionary.
OverflowError -Raised when the result of an arithmetic operation is too large to be
represented.
UnboundLocalError - Raised when a reference is made to a local variable in a function or
method, but no value has been bound to that variable.

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.

Catching Specific Exceptions in Python


For each try block, there can be zero or more except blocks. Multiple except blocks allow us to handle each
exception differently.
The argument type of each except block indicates the type of exception that can be handled by it. For example,
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.

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.

Syntax: assert Expression,[arguments]

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:

The Average of scores2: 75.8


AssertionError: The List is empty.
Python try with else clause:
In some situations, we might want to run a certain block of code if the code block inside try runs without any
errors.For these cases, we can use the optional else keyword with the try statement.

# program to print the reciprocal of even numbers


try:
num = int(input("Enter a number: "))
assert num % 2 == 0
except:
print("Not an even number!")
else:
reciprocal = 1/num
print(reciprocal)

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.

You might also like