Exception Handling
--> Exception is an abnormal event that happens during the execution of the program and stops the program abruptly(Immediately)
--> Exception handling allows to respond to the error, instead of crashing the running program.
Syntax:
try:
# Code that might raise an exception
except SomeException:
# Code to handle the exception
else:
# Code to run if no exception occurs
finally:
# Code to run regardless of whether an exception occurs
try, except, else and finally Blocks
1. try Block
- The try block contains the code that may raise an exception.
If an exception occurs, it is passed to the except block.
2. except BlockThe except block handles exceptions that occur in the try block.
You can specify different types of exceptions or use a general except clause to catch all exceptions.
3. else Block (Optional)
- The else block executes only if no exception occurs in the try block.
4. finally Block (Optional)
- The finally block executes regardless of whether an exception occurs or not.
- It is often used for cleanup actions like closing files or releasing resources.
Examples:
1)
try:
no1 = int(input("Enter no."))
no2 = int(input("Enter no. "))
print(no1//no2)
except ZeroDivisionError:
print("no2 should not be zero. Check no2 Value ")
print(no1+no2)
Output:
Enter no.10
Enter no. 0
no2 should not be zero. Check no2 Value
10
2)
try:
no1 = int(input("Enter no."))
no2 = int(input("Enter no. "))
print(no1//no2)
print(no1+no2)
except ZeroDivisionError:
print("no2 should not be zero. Check no2 Value ")
except ValueError:
print("Inputs should be numbers ")
Output:
Enter no.10
Enter no. ten
Inputs should be numbers
3)
try:
no1 = int(input("Enter no."))
no2 = int(input("Enter no. "))
print(no1//no2)
print(no1+no2)
f = open("pqrs.txt")
except ZeroDivisionError:
print("no2 should not be zero. Check no2 Value ")
except ValueError:
print("Inputs should be numbers ")
except:
print("Something went wrong")
Output:
#if all inputs are correct
Enter no.10
Enter no. 5
2
15
#if any error not specified particularly
Enter no.10
Enter no. 5
2
15
Something went wrong
#if ZeroDivisionError
Enter no.10
Enter no. 0
no2 should not be zero. Check no2 Value
#if ValueError
Enter no.10
Enter no. ten
Inputs should be numbers
Difference between exception handling and conditional statement:
** Note:**
--> Use try-except
when dealing with unpredictable errors
--> Use if-else
when handling expected conditions
Traceback Module:
The traceback module in Python is used to extract, format, and print error traceback information, helping in debugging and logging exceptions.
Example:1
import traceback
try:
no1 = int(input("Enter no."))
no2 = int(input("Enter no. "))
print(no1//no2)
print(no1+no2)
f = open("pqrs.txt")
print(f.read())
except (ValueError, ZeroDivisionError) as msg:
print("Check ",msg)
except:
print("Something went wrong")
traceback.print_exc()
Output:
Enter no.10
Enter no. 0
Check integer division or modulo by zero
Example:2
import traceback
try:
no1 = int(input("Enter no."))
no2 = int(input("Enter no. "))
print(no1//no2)
print(no1+no2)
f = open("pqrs.txt")
print(f.read())
except (ValueError, ZeroDivisionError) as msg:
print("Check ",msg)
except:
print("Something went wrong")
traceback.print_exc()
finally:
print("Check finally message")
Output:
Enter no.10
Enter no. 10
1
20
Something went wrong
Traceback (most recent call last):
File "/home/guru/Desktop/Guru/Python/user.py", line 7, in <module>
f = open("pqrs.txt")
^^^^^^^^^^^^^^^^
FileNotFoundError: [Errno 2] No such file or directory: 'pqrs.txt'
Check finally message
Catching Multiple Specific Exceptions:
--> we can handle multiple exceptions in a single except block using a tuple.
--> using as
we can give a variable name for the exception also.
traceback.print_exc()
: It provides detailed error information (line number, error type, message).
Oops:
Example to display object's memory location:
class Employee:
pass
emp1 = Employee()
emp2 = Employee()
print(emp1)
print(emp2)
Output:
<__main__.Employee object at 0x730a36434110>
<__main__.Employee object at 0x730a36434080>
The pass
keyword means "do nothing" (a placeholder), so the class is currently empty (it has no attributes or methods).
__doc__
(Docstring Attribute)
The __doc__
attribute is used to access the docstring of a class, function, module, or method. A docstring is a multi-line string that provides documentation about the object which is declared inside triple quotes(''' ''').
Example:
class Employee:
'''This class is for creating employees'''
print(Employee.__doc__)
Output:
This class is for creating employees
Self
keyword:
--> “self” is used to access and manipulate the instance variables and methods within a class.
--> Self represents the instance of the class.
Object-Specific
--> Defined using self.variable_name
.
--> Unique for each object.
Example:1
class Employee:
def work(self):
print(self.empName, self.job_nature)
emp1 = Employee()
emp1.empName = 'Guru'
emp1.job_nature = "designing"
emp2 = Employee()
emp2.empName = "Pritha"
emp2.job_nature = "development"
emp1.work()
emp2.work()
Output:
Guru designing
Pritha development
Example:2 class with 3 methods:
class Employee:
organization = "infosys"
def work(self):
print(self.empName, self.job_nature, self.organization)
def take_leave(self):
pass
def promote(self):
pass
emp1 = Employee()
emp1.empName = 'Guru'
emp1.job_nature = "designing"
emp2 = Employee()
emp2.empName = "Pritha"
emp2.job_nature = "development"
emp1.work()
emp2.work()
Output:
Guru designing infosys
Pritha development infosys
class specific information:class-specific information refers to data that is shared among all instances (objects) of a class.
Example:
class Employee:
def work(self):
print(self.empName, self.job_nature, self.organization)
def take_leave(self):
pass
def promote(self):
pass
emp1 = Employee()
emp1.empName = 'Guru'
emp1.job_nature = "designing"
emp2 = Employee()
emp2.empName = "Pritha"
emp2.job_nature = "development"
Employee.organization = "Infosys"
emp1.work()
emp2.work()
Output:
Guru designing Infosys
Pritha development Infosys
Top comments (0)