The try block is used to run code that might raise an error.
The except block catches and handles any errors that occur in the try block.
The else block runs only if no exceptions were raised in the try block.
The finally block executes no matter what—whether an error occurred or not.
Examples:
try:
print(x)
except:
print("An exception occurred")
Multiple Except:
try:
print(x)
except NameError:
print("Variable x is not defined")
except:
print("Something else went wrong")
With Else:
try:
print("Hello")
except:
print("Something went wrong")
else:
print("Nothing went wrong")
Using Finally:
try:
print(x)
except:
print("Something went wrong")
finally:
print("The 'try except' is finished")
Raise an exception
As a Python developer you can choose to throw an exception if a condition occurs.
To throw (or raise) an exception, use the raise keyword.
x = "hello"
if not type(x) is int:
raise TypeError("Only integers are allowed")
def divide_numbers(a, b):
try:
result = a / b
except ZeroDivisionError:
print("Error: Cannot divide by zero.")
else:
print(f"Result is: {result}")
finally:
print("Execution completed.")
# Example usage
divide_numbers(10, 2) # No error
divide_numbers(10, 0) # Triggers exception
Encapsulation is the process of bundling data and methods that operate on that data
within a single unit — typically a class. It helps in hiding internal state and requiring all
interaction to be performed through an object’s methods.
Benefits of Encapsulation:
Improves modularity
Prevents accidental modification
Makes code easier to maintain and debug
class Employee:
def __init__(self, name):
self.Name = name
def set_salary(self,salary):
self.__Salary = salary
def get_salary(self):
return self.__Salary
emp1 = Employee("Mohan")
emp1.set_salary(25000)
emp1.age= 23
print(emp1.get_salary(),emp1.age)
Using @property
class Employee:
allowance = 10000
def __init__(self, name):
self.Name = name
def set_salary(self,salary):
self.__Salary = 10000 + salary
@property
def get_salary(self):
return self.__Salary
emp1 = Employee("Mohan")
emp1.set_salary(25000)
emp1.age= 23
# print(emp1.Name()) #error
print(emp1.get_salary)
# print(emp1.get_salary(),emp1.age)
Using @property and setter
class Employee:
allowance = 10000
def __init__(self, name):
self.Name = name
self.__age = 30
def set_salary(self,salary):
self.__Salary = 10000 + salary
@property
def set_age(self):
return self.__age
@set_age.setter
def set_age(self,a):
self.__age = a
emp1 = Employee("Mohan")
emp1.set_salary(25000)
print (emp1.set_age)
emp1.set_age = 27
print(emp1.set_age)
# print(emp1.Name()) #error
print(emp1.get_salary)
# print(emp1.get_salary(),emp1.age)
Abstraction:
Abstraction means hiding complex implementation details and exposing only the
necessary parts of an object or function.
Benefits of Abstraction
● Simplifies interface
● Reduces complexity
● Improves reusability
Use Case:
● Building APIs
● Game development
● Data analysis tools
● GUI applications
ABCs ensure that subclasses implement specific methods. If they don’t, Python will raise
an error.
ABCs help define a blueprint for other classes. This is useful in large systems where
consistency matters.
from abc import ABC, abstractmethod
class animal(ABC):
@abstractmethod
def speak(self):
print("animal Speaks")
class dog(animal):
def speak(self):
print("Dog barks")
super().speak()
class cat(animal):
def speak(self):
print("cat meow")
def sound(obj):
obj.speak()
d =dog()
c= cat()
sound(d)
sound(c)
sound(animal())
Feature With ABC :
● Compile-time Method enforcement
● Early (safer) Error timing
● Code quality: High (explicit declaration )
● Preferred to Use in real-world projects
Exception Description
ArithmeticError Raised when an error occurs in numeric calculations
AssertionError Raised when an assert statement fails
AttributeError Raised when attribute reference or assignment fails
Exception Base class for all exceptions
EOFError Raised when the input() method hits an "end of file" condition (EOF)
FloatingPointError Raised when a floating point calculation fails
GeneratorExit Raised when a generator is closed (with the close() method)
ImportError Raised when an imported module does not exist
IndentationError Raised when indentation is not correct
IndexError Raised when an index of a sequence does not exist
KeyError Raised when a key does not exist in a dictionary
KeyboardInterrupt Raised when the user presses Ctrl+c, Ctrl+z or Delete
LookupError Raised when errors raised cant be found
MemoryError Raised when a program runs out of memory
NameError Raised when a variable does not exist
NotImplementedError Raised when an abstract method requires an inherited class to override the
method
OSError Raised when a system related operation causes an error
OverflowError Raised when the result of a numeric calculation is too large
ReferenceError Raised when a weak reference object does not exist
RuntimeError Raised when an error occurs that do not belong to any specific exceptions
StopIteration Raised when the next() method of an iterator has no further values
SyntaxError Raised when a syntax error occurs
TabError Raised when indentation consists of tabs or spaces
SystemError Raised when a system error occurs
SystemExit Raised when the sys.exit() function is called
TypeError Raised when two different types are combined
UnboundLocalError Raised when a local variable is referenced before assignment
UnicodeError Raised when a unicode problem occurs
UnicodeEncodeError Raised when a unicode encoding problem occurs
UnicodeDecodeError Raised when a unicode decoding problem occurs
UnicodeTranslateError Raised when a unicode translation problem occurs
ValueError Raised when there is a wrong value in a specified data type
ZeroDivisionError Raised when the second operator in a division is zero