Unit-4 Exceptions Updated1
Unit-4 Exceptions Updated1
The function searches for a pattern in a string and returns a match object if found,
else it returns none.
Syntax: re.match(pattern, string, flags=0)
Example:
import re
usn_list = ['1BM22IS001', '1BM21IS123', '1BM22CS456', '2BM23IS078']
pattern = r'^1BM\d{2}IS\d{3}$’
for usn in usn_list:
if re.match(pattern, usn):
print(f'{usn} is a valid USN.')
else:
print(f'{usn} is NOT a valid USN.')
Python regex flags
Flag long syntax Meaning
Make the DOT (.) special character match any character at all, including a
re.S re.DOTALL
newline. Without this flag, DOT(.) will match anything except a newline
Allow comment in the regex. This flag is useful to make regex more
re.X re.VERBOSE
readable by allowing comments in the regex.
Difference between re.search() and re.match()
• Both functions return the first match of a substring found in the
string, but re.match() searches only from the beginning of the string
and return match object if found.
• But if a match of substring is found somewhere in the middle of the
string, it returns none.
• While re.search() searches for the whole string even if the string
contains multi-lines and tries to find a match of the substring in all
the lines of string.
Compile()
Example:
import re
pattern=re.compile(r'\d+')
result=pattern.findall("123456")
print result
The r in front of the string is called a raw string, which is used to ignore escape
characters.
Sub()
• It returns a string where all matching occurrences of the
specified pattern are replaced by the replace string.
• Syntax: re.sub(pattern, repl, string, count=0, flags=0)
Dept. of ISE 9
Exception Basics …
One use of exceptions is to catch a fault and allow the program to continue
working
Exceptions can be created manually in the code by raising an exception.
Exceptions can be thought of as a special form of the if/elif statements
Proper use of exceptions can help to improve performance of your program
Exceptions also make code management easier
Dept. of ISE 10
Exception Basics …
a = int(input("Enter a:"))
b = int(input("Enter b:"))
c = a/b
print("a/b = %d" %c)
#other code:
print("Hi I am other part of the program")
Output:
Enter a:5
Enter b:0
ERROR!
Traceback (most recent call last):
File "<main.py>", line 5, in <module>
Dept. of ISE
ZeroDivisionError: division by zero 11
Try and Except Statement
• 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:
a = int(input("Enter a:"))
b = int(input("Enter b:"))
c = a/b
except:
print("Can't divide with zero")
#other code:
print("Hi I am other part of the program")
Output:
Enter a:5
Enter b:0
Can't divide with zero
Dept. of ISE Hi I am other part of the program12
Exception example …
Dept. of ISE 13
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.
Syntax
try:
# statement(s)
except IndexError:
# statement(s)
except ValueError:
# statement(s)
Dept. of ISE 14
Exception Basics …
first_number = input ( "Enter the first number: ")
sec_number = input ( "Enter the second number: " )
try :
num1 = float ( first_number )
num2 = float ( sec_number )
result = num1/num2
except ValueError : #not enough numbers entered
print ("Two numbers are required. ")
except ZeroDivisionError : #tried to divide by 0
print ("Zero cannot be a denominator. ")
else :
print (num1, "/ ",num2, "= ", result )
Dept. of ISE 15
Outputs…
Output 1: Output 3:
Enter the first number: 5 Enter the first number: 5
Enter the second number: 0 Enter the second number: 2
5.0 / 2.0 = 2.5
Zero cannot be denominator.
Output 2:
Enter the first number: 5
Enter the second number:
Two numbers are required.
Dept. of ISE 16
Try with Else Clause
• We 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.
Syntax:
try:
# statement(s)
except:
# statement(s)
else:
# statement(s)
Dept. of ISE 17
Exception example
class MyException(Exception):
pass
num = int(input("Enter the marks:"))
try:
if num <0 or num>100:
raise MyException
except MyException as e:
print ("Invalid marks:", num)
else:
Output:
print ("Marks obtained:", num)
Enter the marks:102
Invalid Marks: 102
Dept. of ISE 18
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:
# Some Code....
except:
# optional block
# Handling of exception (if required)
else:
# execute if no exception
finally:
# Some code .....(always executed) Dept. of ISE 19
Example
try:
k = 5//0
print(k)
except ZeroDivisionError:
print("Can't divide by zero")
Output:
finally: Can't divide by zero
print('This is always executed') This is always executed
Dept. of ISE 20
Raising Exception
• Custom exceptions are helpful in many situations.
• They allow to define our own error conditions and handle them in a more specific
and meaningful way.
• We can create a custom exception by creating a new class that inherits from the
built-in Exception class.
• class CustomException(Exception):
pass
• To raise this exception in our code, we can simply use the raise keyword followed
by an instance of the custom exception:
• raise CustomException('This is a custom exception')
Dept. of ISE 21
Example: Exception that handles negative
numbers in squareroot operation
User Defined Exceptions …
try:
input_num = int(input("Enter a number: "))
if input_num < number:
raise InvalidAgeException
else:
print("Eligible to Vote") Output:
Enter a number: 15
except InvalidAgeException: Exception occurred: Invalid Age
print("Exception occurred: Invalid Age")
Dept. of ISE 24
# Define a custom exception class
class NotEnoughBalanceError(Exception):
def __init__(self, balance, amount):
User Defined Exceptions …
self.balance = balance
self.amount = amount
super().__init__(f"Not enough balance ({balance}) to withdraw {amount}")
# Example class representing a bank account
class BankAccount:
def __init__(self, balance):
self.balance = balance
def withdraw(self, amount):
if self.balance < amount:
raise NotEnoughBalanceError(self.balance, amount)
Output1:
self.balance -= amount
Enter the amount to be withdrawn: 1500
return self.balance
Not enough balance (1000) to withdraw 1500
# Example usage Output2:
try: Enter the amount to be withdrawn: 500
account = BankAccount(1000) Withdrew 500. Remaining balance: 500
withdrawal_amount = int(input("Enter the amount to be withdrawn: "))
remaining_balance = account.withdraw(withdrawal_amount)
print(f"Withdrew {withdrawal_amount}. Remaining balance: {remaining_balance}")
except NotEnoughBalanceError as e:
Dept. of ISE 25
print(e)
Examples
• 1. Input a number from the keyboard and raise an exception
if the input is not a number.
• 2. Write a python program that accepts two numbers from
the user and performs their division. It should raise an
exception for division by zero error, value error and have a
finally block.
• Write a program to demonstrate the use of try, except and
else in python exception handling.
Examples
• Write a python program to check the validity of the age. Raise an
exception if the entered age is less than 0.
• Write a Python program that demonstrates handling of exceptions
in inheritance tree. Create a base class called “Father” and a derived
class called “Son” which extends the base class. In Father class,
implement a constructor which takes the age and throws the
exception WrongAge( ) when the input age<0. In Son class,
implement a constructor that checks both father and son’s age and
throws an exception if son’s age is greater than or equal to father’s
age.
Exception Class Hierarchy
• When an exception occurs, it starts at the lowest level possible (a child) and
travels upward (through the parents), waiting to be caught.
1. If you don’t know what exception may occur, you can always just catch a
higher level exception. if you didn’t know that ZeroDivisionError, you could
have used the ArithmeticError for the exception and caught that
(ZeroDivisionError is a child of ArithmeticError)
2. Multiple exceptions can be treated the same way. suppose you plan on
using the ZeroDivisionError and you want to include the FloatingPointError.
If you wanted to have the same action taken for both errors, simply use the
parent exception ArithmeticError as the exception to catch.
Dept. of ISE 28
Exception Class Hierarchy …
Dept. of ISE 29