[go: up one dir, main page]

0% found this document useful (0 votes)
3 views14 pages

Unit 5-1

The document covers Exception Handling and Object-Oriented Programming (OOP) in Python. It explains the importance of exception handling, the use of try-except blocks, and key OOP concepts such as classes, objects, encapsulation, inheritance, polymorphism, and abstraction. Additionally, it provides examples for each concept to illustrate their application in Python programming.

Uploaded by

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

Unit 5-1

The document covers Exception Handling and Object-Oriented Programming (OOP) in Python. It explains the importance of exception handling, the use of try-except blocks, and key OOP concepts such as classes, objects, encapsulation, inheritance, polymorphism, and abstraction. Additionally, it provides examples for each concept to illustrate their application in Python programming.

Uploaded by

krashan.042732
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 14

Python Theory Notes: Exception Handling & OOP

Exception Handling in Python

1. What is Exception Handling?

Exception handling in Python allows programmers to manage and respond to unexpected

events or errors during program execution, without crashing the program. These errors are

known as exceptions.

2. Why is Exception Handling Important?

- Prevents program from terminating unexpectedly.

- Provides meaningful error messages to users.

- Allows graceful recovery from unexpected errors.

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:

print("Cannot divide by zero")

4. Catching Multiple Exceptions:

You can handle multiple exception types separately using multiple except blocks.
Python Theory Notes: Exception Handling & OOP

Example:

try:

value = int(input("Enter a number:

")) result = 10 / value

except ValueError:

print("Invalid input! Please enter a

number.") except ZeroDivisionError:

print("Division by zero is not allowed.")

5. Finally Block:

A finally block contains code that will always execute, regardless of whether an exception was

raised or not. It is useful for clean-up activities.

Example:

try:

x = 10 / 2

except:

print("Something went wrong")

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:

")) except ValueError:

print("Invalid

input") else:
Python Theory Notes: Exception Handling & OOP

print("Valid input")

7. Raising Exceptions:

You can raise custom exceptions using the raise keyword.

Example:

if age < 0:

raise ValueError("Age cannot be negative")

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:

raise NegativeValueError("Negative values not allowed")

Error & Exceptions:

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.

Disrupting Normal Flow:


Exceptions interrupt the normal execution path of the program.

Handled with try-except:


Python provides try-except blocks to handle exceptions, allowing the program to continue
executing even after encountering an error.

Examples:
ZeroDivisionError, FileNotFoundError, TypeError.
Python Theory Notes: Exception Handling & OOP

Object-Oriented Programming (OOP) in Python

1. What is Object-Oriented Programming (OOP)?

OOP is a programming paradigm based on the concept of "objects", which contain data

(attributes) and code (methods) that operates on the data.

2. Key Concepts of OOP:

- Class

- Object

- Encapsulation
Python Theory Notes: Exception Handling & OOP

Inheritance

- Polymorphism

- Abstraction

3. Class and Object:

A class is a blueprint for creating objects. An object is an instance of a class.

Example:

class Car:

def init (self, brand):

self.brand = brand

def start(self):

print(f"{self.brand} car started")

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

single unit. Encapsulation is achieved through access modifiers:

Public: Accessible from anywhere.

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.

Private members are prefixed with an underscore (_) or double underscore ( ).

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

Example: class Shape:

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 in Python, a key principle of object-oriented programming, focuses on simplifying


complex systems by exposing only essential information to the user while hiding unnecessary
implementation details. This is achieved through abstract classes and methods.
n abstract class cannot be instantiated directly and serves as a blueprint for other classes. It
may contain abstract methods, which are declared but not defined in the abstract class, and
must be implemented by its subclasses. The abc module in Python provides the necessary tools
for defining abstract classes and methods.

Abstraction hides the internal details and shows only the functionality.

from abc import ABC,

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

# Attempting to instantiate Shape will raise a


TypeError # shape = Shape()
Python Theory Notes: Exception Handling & OOP

circle = Circle(5)
print(f"Circle area: {circle.area()}")
print(f"Circle perimeter:
{circle.perimeter()}")

square = Square(4)
Python Theory Notes: Exception Handling & OOP

print(f"Square area: {square.area()}")


print(f"Square perimeter:
{square.perimeter()}")

8. Constructor ( init method):

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:

def init (self, name):

self.name = name

s = Student("Alice")

You might also like