Unit 5-1
Unit 5-1
events or errors during program execution, without crashing the program. These errors are
known as exceptions.
3. Try-Except Block:
The try-except block is used to catch and handle exceptions. Code that might raise an
exception is placed inside the try block. If an exception occurs, the except block is executed.
Syntax:
try:
# risky code
except
ExceptionType: #
handling code
Example:
try:
x=5/0
except ZeroDivisionError:
You can handle multiple exception types separately using multiple except blocks.
Python Theory Notes: Exception Handling & OOP
Example:
try:
except ValueError:
5. Finally Block:
A finally block contains code that will always execute, regardless of whether an exception was
Example:
try:
x = 10 / 2
except:
finally:
print("Execution completed.")
6. Else Clause:
The else block runs only if the try block does not raise an exception.
Example:
try:
x = int(input("Enter number:
print("Invalid
input") else:
Python Theory Notes: Exception Handling & OOP
print("Valid input")
7. Raising Exceptions:
Example:
if age < 0:
8. User-Defined Exceptions:
Custom exceptions are created by defining a new class that inherits from the Exception class.
Example:
class
NegativeValueError(Exception):
pass
num = -
1 if num
< 0:
In Python, errors are broader problems that prevent code from running at all, often detected
during compilation or interpretation. Exceptions are specific runtime errors that interrupt the
program's normal flow but can be handled and recovered from during execution. Errors usually
require code fixes, while exceptions are handled using try-except blocks
Errors:
Syntax Errors:
These occur when the code violates the rules of Python's grammar, like a missing colon or
incorrect indentation. They are detected before the code even runs and prevent execution.
Logical Errors:
These are mistakes in the program's logic, where it doesn't produce the expected result even
though the code is syntactically correct. These are harder to detect and require debugging.
Unrecoverable Errors:
Python Theory Notes: Exception Handling & OOP
Errors often indicate a system issue beyond the program's control and cannot be handled
gracefully.
Python Theory Notes: Exception Handling & OOP
Exceptions:
Runtime Errors:
Exceptions are errors that occur during the execution of the program, after the code has been
successfully parsed and is running.
Examples:
ZeroDivisionError, FileNotFoundError, TypeError.
Python Theory Notes: Exception Handling & OOP
OOP is a programming paradigm based on the concept of "objects", which contain data
- Class
- Object
- Encapsulation
Python Theory Notes: Exception Handling & OOP
Inheritance
- Polymorphism
- Abstraction
Example:
class Car:
self.brand = brand
def start(self):
my_car =
Car("Toyota")
my_car.start()
4. Encapsulation:
Encapsulation in Python is a mechanism of bundling data (attributes) and methods that operate
on that data into a single unit (class). It restricts direct access to some of an object's
components and prevents the accidental modification of data. It promotes data hiding and
abstraction, making the code more manageable and secure.
Encapsulation is the process of wrapping data and the methods that operate on that data into a
Protected: Accessible within the class and its subclasses. Denoted by a single underscore prefix,
e.g.,
_attribute.
Private: Accessible only within the class. Denoted by a double underscore prefix, e.g., attribute.
Example:
class
Python Theory Notes: Exception Handling & OOP
BankAccount:
def init
(self):
self_____balance = 0
Python Theory Notes: Exception Handling & OOP
def deposit(self,
amount): self.
balance += amount
def show_balance(self):
print("Balance:", self.
balance)
Python Theory Notes: Exception Handling & OOP
5. Inheritance:
Inheritance in Python is a mechanism where a new class (child class or subclass) acquires
attributes and methods from an existing class (parent class or superclass). It facilitates code
reuse and establishes a hierarchy among classes.
Python supports single, multiple, and multilevel inheritance. In multiple inheritance, a class can
inherit from multiple parent classes.
Example:
class Animal:
def speak(self):
print("Animal speaks")
class
Dog(Animal):
def bark(self):
print("Dog barks")
d=
Dog()
d.speak
()
d.bark()
6. Polymorphism:
Polymorphism means many forms. It allows methods to do different things based on the object
calling them.
It
refers to the ability of a single function, method, object, or operator to manifest in various forms.
In essence, it allows a single action to behave differently depending on the object it is applied to
Method Overriding
def area(self):
print("Calculating
area")
Python Theory Notes: Exception Handling & OOP
class
Circle(Shape):
def area(self):
print("Area of Circle")
s = Circle()
Python Theory Notes: Exception Handling & OOP
s.area()
7. Abstraction:
Abstraction hides the internal details and shows only the functionality.
abstractmethod class
Shape(ABC):
@abstractmetho
d def area(self):
pass
@abstractmetho
d def
perimeter(self):
pass
class Circle(Shape):
def init (self, radius):
self.radius = radius
def area(self):
return 3.14 * self.radius * self.radius
def perimeter(self):
return 2 * 3.14 * self.radius
class Square(Shape):
def init (self,
side):
self.side = side
def area(self):
return self.side * self.side
def
perimeter(self):
return 4 *
self.side
circle = Circle(5)
print(f"Circle area: {circle.area()}")
print(f"Circle perimeter:
{circle.perimeter()}")
square = Square(4)
Python Theory Notes: Exception Handling & OOP
In Python, a constructor is a special method within a class that initializes the attributes of an
object when it is created. It is automatically called when an object of the class is instantiated.
The constructor method is named
init .
Example:
class Student:
self.name = name
s = Student("Alice")