0% found this document useful (0 votes)
19 views21 pages

Python Exception Handling Guide

The document discusses exception handling in Python, explaining the types of errors (syntax and logical) and various built-in exceptions such as SyntaxError, TypeError, and ValueError. It covers the use of try-except statements for catching exceptions, the use of else and finally clauses, and the ability to raise exceptions. Additionally, it highlights the advantages and disadvantages of exception handling and introduces user-defined exceptions.

Uploaded by

ashopn2006
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
19 views21 pages

Python Exception Handling Guide

The document discusses exception handling in Python, explaining the types of errors (syntax and logical) and various built-in exceptions such as SyntaxError, TypeError, and ValueError. It covers the use of try-except statements for catching exceptions, the use of else and finally clauses, and the ability to raise exceptions. Additionally, it highlights the advantages and disadvantages of exception handling and introduces user-defined exceptions.

Uploaded by

ashopn2006
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Exception Handling

1
Errors in Python
 Errors are the problems in a program due to which the program
will stop the execution.
 Two types of Error occurs in python.
 Syntax errors (parsing errors)
 Logical errors (Exceptions)
 When the proper syntax of the language is not followed then a
syntax error occurs.
 Exceptions are raised when some internal events occur after
passing the syntax test which change the normal flow of the
program.
2
Syntax Error
amount = 10000

if(amount > 2999)


print("You are eligible to purchase Dsa Self
Paced")

#corrected snippet
amount = 10000

if(amount > 2999):


print("You are eligible to purchase Dsa Self Paced")

3
Built-in Exceptions
 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.
4
Built-in Exceptions
 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.
 AttributeError: This exception is raised when an attribute or
method is not found on an object, such as trying to access a non-
existent attribute of a class instance.

5
Built-in Exceptions
 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.

6
Try and Except Statement – Catching Exceptions
 Try and except statements are used to catch and handle
exceptions in Python.
 Statements that can raise exceptions are kept inside the try
clause and the statements that handle the exception are written
inside except clause.
 try:
 # statement(s)
 except:
 # statement(s)

7
Simple Exception Handling
marks = 10000

a = marks / 0
print(a)

marks = 10000
try:
a = marks / 0
except:
print("Can't divide. Zero Division Error occurs")

Output:
Can't divide. Zero Division Error occurs

8
Sample Programs
x=5
y = "hello"
try:
z=x+y
except TypeError:
print("Error: cannot add an int and a
str")

a = [1, 2, 3]
try:
print ("Second element = %d" %(a[1]))
print ("Fourth element = %d" %(a[3]))
except:
print ("An error occurred")

9
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.
 The general syntax for adding specific exceptions are –
 try:
 # statement(s)
 except IndexError:
 # statement(s)
 except ValueError:
 # statement(s)
10
Catching Specific Exception
def fun(a):
if a < 4:
 b = a/(a-3)
 print("Value of b = ", b)
 try:
 fun(3)
 fun(5)
 except ZeroDivisionError:
 print("ZeroDivisionError Occurred and Handled")
 except NameError:
 print("NameError Occurred and Handled")
11
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.
 try:
 # Some Code....
 except:
 # optional block
 # Handling of exception (if required)
 else:
 # execute if no exception

12
Try with Else Clause
def AbyB(a , b):
try:
c = ((a+b) / (a-b))
except ZeroDivisionError:
print ("a/b result in
0")
else:
print (c)

# Driver program to test above function


AbyB(2.0, 3.0)
Output:
AbyB(3.0, 3.0) -5.0
a/b result in 0

13
Finally Keyword
 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: Example:
# Some Code....
except: try:
# optional block k = 5//0 # raises divide by zero exception.
# Handling of exception (if required) print(k)
else: except ZeroDivisionError:
# execute if no exception print("Can't divide by zero")
finally:
finally:
# Some code .....(always executed)
print('This is always executed')

14
Raising Exceptions
 The raise statement allows the programmer to force a specific
exception to occur.
 The sole argument in raise indicates the exception to be raised.
 This must be either an exception instance or an exception class (a
class that derives from Exception).
try:
raise NameError("Hi there") # Raise
Error An exception
except NameError: Traceback (most recent call last):
print ("An exception") File "<string>", line 4, in <module>
raise ERROR!
NameError: Hi there

15
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 traceback that shows the exact location where the exception
occurred, making it easier to debug your code.
16
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.
 Possible security risks: Improperly handled exceptions can
potentially reveal sensitive information or create security
vulnerabilities in your code, so it’s important to handle exceptions
carefully and avoid exposing too much information about your
program.
17
Multiple Exception Handling
 Can handle different exceptions all using a single block of code,
by grouping together in a tuple
 ... except (RuntimeError, TypeError, NameError):
 ........pass
Example
try:
client_obj.get_url(url)
except (URLError, ValueError):
client_obj.remove_url(url)
except SocketTimeout:
client_obj.handle_url_tim
eout(url)
18
User-Defined Exception
 Can define custom exceptions by creating a new class that is derived from the built-in
Exception class.

 Here's the syntax to define custom exceptions,


class CustomError(Exception):
...
pass
try:
...
except CustomError:
...
 Here, CustomError is a user-defined error which inherits from the
Exception class.

19
User-Defined Exception
class InvalidAgeException(Exception):
"Raised when the input value is less than 18"
pass
number = 18
try:
Output
input_num = int(input("Enter a number: ")) #If the user input input_num is greater than 18,
Enter a number: 45
if input_num < number:
Eligible to Vote
raise InvalidAgeException
#If the user input input_num is smaller than 18,
else:
Enter a number: 14
print("Eligible to Vote") Exception occurred: Invalid Age

except InvalidAgeException:
print("Exception occurred: Invalid Age")

20
User-Defined Exception
class SalaryNotInRangeError(Exception):
"""Exception raised for errors in the input salary.

Attributes:
salary -- input salary which caused the error
message -- explanation of the error
"""

def __init__(self, salary, message="Salary is not in (5000, 15000) range"):


[Link] = salary
[Link] = message
super().__init__([Link]) Output
Enter salary amount: 2000
salary = int(input("Enter salary amount: ")) Traceback (most recent call last):
if not 5000 < salary < 15000: File "<string>", line 17, in <module>
raise SalaryNotInRangeError(salary)
raise SalaryNotInRangeError(salary)

__main__.SalaryNotInRangeError: Salary is not in (5000, 15000) range

21

You might also like