NOTES - Exception Handling
NOTES - Exception Handling
Errors are problems in a program due to which the program will stop
the execution.
On the other hand, exceptions are raised when some internal events
occur which change the normal flow of the program.
Advantages of Exception Handling:
• Improved program reliability: By handling exceptions properly, you can
prevent your program from crashing or producing incorrect results due to
unexpected errors or input.
• Simplified error handling: Exception handling allows you to separate error
handling code from the main program logic, making it easier to read and
maintain your code.
• Cleaner code: With exception handling, you can avoid using complex
conditional statements to check for errors, leading to cleaner and more
readable code.
• Easier debugging: When an exception is raised, the Python interpreter
prints a trace back that shows the exact location where the exception
occurred, making it easier to debug your code.
Disadvantages of Exception Handling:
• Performance overhead: Exception handling can be slower than using
conditional statements to check for errors, as the interpreter has to
perform additional work to catch and handle the exception.
• Increased code complexity: Exception handling can make your code more
complex, especially if you have to handle multiple types of exceptions or
implement complex error handling logic.
Different types of exceptions in python:
In Python, there are several built-in exceptions that can be raised when an error occurs during
the execution of a program. Here are some of the most common types of exceptions in Python:
• SyntaxError: This exception is raised when the interpreter encounters a syntax error in the
code, such as a misspelled keyword, a missing colon, or an unbalanced parenthesis.
• TypeError: This exception is raised when an operation or function is applied to an object of
the wrong type, such as adding a string to an integer.
• NameError: This exception is raised when a variable or function name is not found in the
current scope.
• IndexError: This exception is raised when an index is out of range for a list, tuple, or other
sequence types.
• KeyError: This exception is raised when a key is not found in a dictionary.
• ValueError: This exception is raised when a function or method is called with an invalid
argument or input, such as trying to convert a string to an integer when the string does not
represent a valid integer.
• IOError: This exception is raised when an I/O operation, such as reading or writing a file, fails
due to an input/output error.
• ZeroDivisionError: This exception is raised when an attempt is made to divide a number by
zero.
• ImportError: This exception is raised when an import statement fails to find or load a
module.
Difference between Syntax Error and Exceptions
Syntax Error
As the name suggests this error is caused by the wrong syntax in the code. It leads
to the termination of the program.
a = [1,2,3]
try:
print ("Second element",a[1])
# Throws error since there are only 3 elements in array
print ("Fourth element",a[3])
OUTPUT:
except: Second element 2
An error occurred
print ("An error occurred")
Catching Specific Exception
A try statement can have more than one except clause, to specify
handlers for different exceptions. Please note that at most one handler
will be executed.
For example, we can add IndexError in the above code. The general
syntax for adding specific exceptions are –
try:
# statement(s)
except IndexError:
# statement(s)
except ValueError:
# statement(s)
Example: Catching specific exceptions in the Python
# Program to handle multiple errors with one except statement
def fun(a):
if a < 4:
# throws ZeroDivisionError for a = 3
b = a/(a-3)
# throws NameError if a >= 4
print("Value of b = ", b)
try:
fun(2)
fun(5)
except ZeroDivisionError:
print("ZeroDivisionError Occurred and Handled")
except NameError:
print("NameError Occurred and Handled")
Try with Else Clause
In Python, you can also use the else clause on the try-except block which must be
present after all the except clauses. The code enters the else block only if the try
clause does not raise an exception.
fun(2.0, 3.0)
fun(3.0, 3.0)
Finally Keyword in Python
Python provides a keyword finally, which is always executed after the try and
except blocks. The final block always executes after the normal termination
of the try block or after the try block terminates due to some exception.
Syntax:
try:
# Some Code....
except:
# optional block
# Handling of exception (if required)
else:
# execute if no exception
finally:
# Some code .....(always executed)
try:
k = 5//0 # raises divide by zero exception.
print(k)
finally:
# this block is always executed
# regardless of exception generation.
print('This is always executed')