0% found this document useful (0 votes)
2 views15 pages

Unit3 Python

The document discusses exceptions in Python, detailing various types of errors such as syntax errors and runtime exceptions, along with built-in exceptions like ImportError and ZeroDivisionError. It explains how to handle exceptions using try, except, else, and finally blocks, and introduces the concept of raising exceptions, including user-defined exceptions. Additionally, the document covers the basics of object-oriented programming in Python, including classes, objects, and the use of constructors.

Uploaded by

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

Unit3 Python

The document discusses exceptions in Python, detailing various types of errors such as syntax errors and runtime exceptions, along with built-in exceptions like ImportError and ZeroDivisionError. It explains how to handle exceptions using try, except, else, and finally blocks, and introduces the concept of raising exceptions, including user-defined exceptions. Additionally, the document covers the basics of object-oriented programming in Python, including classes, objects, and the use of constructors.

Uploaded by

veena more
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

UNIT 3 EXCEPTIONS AND OBJECT ORIENTED PROGRAMMING 1

EXCEPTION IN PYTHON
• While writing a program, we often end up making some errors.
• There are many types of errors that can occur in a program.
• The error caused by writing an improper syntax is termed syntax error or parsing
error; these are also called compile time errors.
• Errors can also occur at runtime and these runtime errors are known as
Exceptions.
• There are various types of runtime errors in python. Let us look at a few
examples.
 When a file we try to open does not exist, we get a filenotfounderror.
 When a division by zero happens, we get a zerodivisionerror.
 When the module we are trying to import does not exist, we get an
importerror.
• Python creates an exception object for every occurrence of these run-time errors.
• The user must write a piece of code that can handle the error.
• If it is not capable of handling the error, the program prints a trace back to that
error along with the details of why the error has occurred.

• The error shown above is a syntax error because there is a problem with the
syntax; the if statement starts with semicolon.
zerodivisionerror
>>> 5/0
OUTPUT
Traceback (most recent call last):
File "<pyshell#71>", line 1, in <module>

[Link] College of Commerce (Autonomous), Vijayapur BCA


Programme
UNIT 3 EXCEPTIONS AND OBJECT ORIENTED PROGRAMMING 2

5/0
ZeroDivisionError: integer division or modulo by zero
• Here, we tried to divide 5 by 0. As a result, the interpreter prints
zerodivisionerror.
• Python provides a very important feature (exception handling) for
handling any unexpected error in our python programs, and it also adds
debug capabilities to them.

BUILT-IN EXCEPTIONS
• Any error prone statement can raise exception.
• There are various built-in exceptions in python that can be raised when the
corresponding errors occur.
• Table gives the full list of built-in exceptions in python.

SLNO EXCEPTION CAUSE OF ERROR

1 ImportError Raised when imported module does not exist.

2 IndexError Raised when an index of sequence is out of range or not found

3 KeyError Raised when key does not exist in a dictionary.

4 SyntaxError Raised by parser on a syntax error

5 IndentationError Raised when there is an incorrect indentation.

6 ZeroDivisionError Raised when a number is divided by zero.

7 FloatingPoint Raised when a floating point operation fails.


Error

8 RuntimeError Raised when an error doesn’t fall in any other category.

9 SystemError Raised when an internal error occurred.

[Link] College of Commerce (Autonomous), Vijayapur BCA


Programme
UNIT 3 EXCEPTIONS AND OBJECT ORIENTED PROGRAMMING 3

10 StopIteration Raised when there is no next item to be iterated by iterator.

HANDLING EXCEPTIONS
 Whenever an exception occurs in python, it stops the current process and
passes it to the calling process until it is handled.
 If there is no piece of code in your program that can handle the exception,
then the program will crash.
 Python provides a very important feature (exception handling) for
handling any unexpected error in our python programs, and it also adds
debug capabilities to them.
blocks
• The try block lets you test a block of code for errors.
• The except block lets you handle the error.
• The else block lets you execute code when there is no error.
• The finally block lets you execute code, regardless of the result of the
try- and except blocks.
TRY BLOCK & EXCEPT BLOCK
 Python provides a try statement for handling exceptions.
 An operation in the program that can cause the exception is placed in the
try clause while the block of code that handles the exception is placed in
the except clause.
 The block of code for handling the exception is written by the user and it
is for him to decide which operation he wants to perform after the
exception has been identified.“
EXAMPLE:
try:
print(x)
except:
print("An exception occurred")
OUTPUT:

[Link] College of Commerce (Autonomous), Vijayapur BCA


Programme
UNIT 3 EXCEPTIONS AND OBJECT ORIENTED PROGRAMMING 4

An exception occurred #The try block will generate an error, because x is not
defined:

EXCEPT WITH MULTIPLE EXCEPTIONS


 A try block can have multiple except clauses associated with it.
 It can be useful to have the try block include statements that can cause
different types of exceptions.
 After except clause, we can add an else statement .
 The statements in the else block will execute only when the statements in
try block do not raise any exception.
Exception Arguments
• Except: → Catches All Errors But Hides The Cause.
• Except Exception As E: → Catches All Errors And Shows What
Happened.
EXAMPLE:
try:
num1 = int(input("Enter first number: "))
num2 = int(input("Enter second number: "))
result = num1 / num2
print("Result:", result)
except ValueError:
print("Error: Please enter valid integers.")
except ZeroDivisionError:
print("Error: Division by zero is not allowed.")
except Exception as e:
print("An unexpected error occurred:", e)
• ValueError → Raised if the user enters something that cannot be
converted to an integer.
• ZeroDivisionError → Raised if the user tries to divide by zero.
[Link] College of Commerce (Autonomous), Vijayapur BCA
Programme
UNIT 3 EXCEPTIONS AND OBJECT ORIENTED PROGRAMMING 5

• Exception → Catches any other unexpected error.

Except with No Exception :


 We can also write our try–except clause with no Exception.
 All types of exceptions that occur are caught by the try–except
Statement.
 However, because it catches all exceptions, the programmer cannot
Identify the root cause of a problem that may occur.
 Hence, this type of programming approach is not Considered good."
EXAMPLE:
try:
num = int("abc") # This will cause ValueError
result = 10 / 0 # This will cause ZeroDivisionError
except:
print("Something went wrong!")
OUTPUT:
Something went wrong!

ELSE BLOCK
The else block runs only if no exception occurs inside the try block.
EXAMPLE:
try:
num = int(input("Enter a number: "))
result = 10 / num
except ValueError:
print("Error: Please enter a valid integer.")
except ZeroDivisionError:
[Link] College of Commerce (Autonomous), Vijayapur BCA
Programme
UNIT 3 EXCEPTIONS AND OBJECT ORIENTED PROGRAMMING 6

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


else:
print("Success! Result is:", result)
Output:
If input = 2
Success! Result is: 5.0
If input = abc
Error: Please enter a valid integer.
If input = 0
Error: Division by zero is not allowed.

FINALLY BLOCK
• The finally block is used to write code that must run no matter what
happens:
 Whether an exception occurs or not
 Whether it is handled or not
• Commonly used for cleanup actions (closing files, releasing resources,
disconnecting from databases, etc.).
EXAMPLE:
try:
num = int(input("Enter a number: "))
result = 10 / num
except ZeroDivisionError:
print("Error: Cannot divide by zero.")
finally:
print("This block always runs.")
OUTPUT:
IF input = 2
[Link] College of Commerce (Autonomous), Vijayapur BCA
Programme
UNIT 3 EXCEPTIONS AND OBJECT ORIENTED PROGRAMMING 7

This block always runs.


IF input = 0
Error: Cannot divide by zero.
This block always runs.

EXAMPLE: with try, except, finally, else


try:
num = int(input("Enter a number: "))
result = 10 / num
except ValueError:
print("Error: Please enter a valid integer.")
except ZeroDivisionError:
print("Error: Division by zero is not allowed.")
else:
print("Success! The result is:", result)
finally:
print("This block always runs (cleanup).")
OUTPUT
Case 1: Input = 5
Success! The result is: 2.0
This block always runs (cleanup).
No error → else runs → finally runs.
Case 2: Input = abc
Error: Please enter a valid integer.
This block always runs (cleanup).
Case 3: Input = 0
Error: Division by zero is not allowed.

[Link] College of Commerce (Autonomous), Vijayapur BCA


Programme
UNIT 3 EXCEPTIONS AND OBJECT ORIENTED PROGRAMMING 8

This block always runs (cleanup).


ZeroDivisionError → handled by except → finally still runs.

RAISING AN EXCEPTION
• In python, you can raise exceptions explicitly using the raise statement.
• In python, raise is a keyword used to manually trigger (raise) an exception.
• It allows you to stop the normal flow of a program when something goes wrong,
or when you want to enforce certain conditions.
• In python, you can raise built-in exceptions like valueerror or typeerror to
indicate common error conditions.
• Additionally, you can create and raise custom exceptions.
In short:
• Exception → The actual error (object).
• raise → The action (keyword) used to throw that error.

SYNTAX
raise ExceptionType("Error message")
• Exceptiontype → the type of error (like valueerror, typeerror, runtimeerror, or
even a custom exception).
• "Error message" → an optional message to describe what went wrong.
Example 1: Raise a built-in exception
x = -5
if x < 0:
raise ValueError("x cannot be negative")
OUTPUT:
ValueError: x cannot be negative

Example 2: Custom Exception


[Link] College of Commerce (Autonomous), Vijayapur BCA
Programme
UNIT 3 EXCEPTIONS AND OBJECT ORIENTED PROGRAMMING 9

• You can define your own exception class:


class MyCustomError(Exception):
pass
def check_age(age):
if age < 18:
raise MyCustomError("Age must be at least 18")
check_age(15)
OUTPUT
MyCustomError: Age must be at least 18

USERDEFINED EXCEPTION
• User-defined exceptions in python, also known as custom exceptions, are created to
handle specific error conditions that are not adequately covered by python's built-in
exceptions.
• They provide a way to make error handling more precise and understandable within
an application.
EXAMPLE:
class MyCustomError(Exception):
pass
def check_number(num):
if num < 0:
raise MyCustomError("Negative numbers are not allowed!")
try:
check_number(-10)
except MyCustomError as e:
print("Caught custom exception:", e)
OUTPUT:
Caught custom exception: Negative numbers are not allowed!
[Link] College of Commerce (Autonomous), Vijayapur BCA
Programme
UNIT 3 EXCEPTIONS AND OBJECT ORIENTED PROGRAMMING 10

OBJECT ORIENTED PROGRAMMING


• Python is an object-oriented programming (OOP) language and provides all the
features required to support object-oriented programming.
• OOP mainly focuses on the objects and classes while procedural programming
focuses on the functions and methods.
• Oop is based on the implementation of real world objects in programming.
• In this approach, a problem is considered in terms of objects that can be
involved in finding the solution to the problem instead of procedures.
• Hence, through this approach, a person can relate a problem to the real world
objects and can work towards its solution with relative ease.
• Object is an instance of a class. A class is a collection of data (variables) and
methods (functions).
• Let us understand the concept with an example.
• We can relate class to a sketch or model of a building.
• That sketch contains all the information about the structure of the building, such
as floors, doorways, exits, rooms, etc.
• Now, according to our example, the building is an object. Just as various
buildings can be based on one model, so too can a class have many objects
associated with it.

What is a class?
• A blueprint/template for creating objects.
What is an object?
• An instance of a class.
Create a class
• To create a class, use the keyword class:
• Create a class named myclass, with a property named x:
[Link] College of Commerce (Autonomous), Vijayapur BCA
Programme
UNIT 3 EXCEPTIONS AND OBJECT ORIENTED PROGRAMMING 11

class MyClass:
x=5

Create object
• Now we can use the class named myclass to create objects:
Example:Create an object named p1, and print the value of x:
class Myclass:
x=5
p1 = Myclass()
print(p1.x)
OUTPUT:
5

Defining a Class
In python, a class is defined using the class keyword:
class ClassName:
# class body (variables + methods)
pass
• Classname → name of the class (should start with a capital letter by convention).
• pass → placeholder (used when you don’t want to put anything yet).
EXAMPLE
class Student:
pass
# creating objects
s1 = Student()
s2 = Student()
print(type(s1)) # <class '__main__.Student'>

[Link] College of Commerce (Autonomous), Vijayapur BCA


Programme
UNIT 3 EXCEPTIONS AND OBJECT ORIENTED PROGRAMMING 12

print(type(s1))
• The built-in type() function tells what class/type an object belongs to.
• Since s1 was created from student, its type is student.
• Python also shows where the class was defined (__main__ means it was created
in the current running file/program).

Class with Variables and Methods


class Car:
# method
def start(self):
print("Car is starting...")
# create object
mycar = Car()
[Link]() # Output: Car is starting...

CLASS WITH INIT AND METHODS


class Student:
# constructor (special method)
def __init__(self, name, age):
[Link] = name # instance variable
[Link] = age
def display(self):
print(f"Name: {[Link]}, Age: {[Link]}")
s1 = Student("Alice", 20) # object 1
s2 = Student("Bob", 22) # object 2
[Link]() # Output: Name: Alice, Age: 20
[Link]() # Output: Name: Bob, Age: 22

[Link] College of Commerce (Autonomous), Vijayapur BCA


Programme
UNIT 3 EXCEPTIONS AND OBJECT ORIENTED PROGRAMMING 13

Explanation
• __init__ method (constructor)
• Runs automatically whenever an object is created.
• Used to initialize data for that object.
• Self refers to the current object.
• Instance variables ([Link], [Link])
• Belong to each object individually.
• Each student object will have its own name and age.
• Methods (like display)
• Functions inside a class.
• Work on the data stored in the object.

CLASS VARIABLES (Without __init__ and self)


• declared outside any method, directly inside the class.
• shared by all objects of the class.
• belong to the class itself, not to individual objects.
• You can create a class with only class variables:
class MyClass:
x = 5 # class variable
p1 = MyClass()
print(p1.x) # Output: 5
• Here, we never used __init__ or self. The variable x belongs to the class, and
every object can access it.

INSTANCE VARIABLES(With __init__ and self)


If you want each object to have its own data (instance variables), you use
__init__ and self:
[Link] College of Commerce (Autonomous), Vijayapur BCA
Programme
UNIT 3 EXCEPTIONS AND OBJECT ORIENTED PROGRAMMING 14

• declared inside the __init__ method using self.


• unique for each object (every object can have different values).
• belong to a specific object/instance
class MyClass:
def __init__(self, value):
self.x = value # instance variable
p1 = MyClass(5)
p2 = MyClass(10)
print(p1.x) # Output: 5
print(p2.x) # Output: 10

The super() Function


• used to call a method or constructor from the parent class.
• especially useful when child class overrides methods of parent.
Inheritance super() function
• Inheritance allows a class (child class) to reuse the properties and
methods of another class (parent/base class).
class Person: # Parent class
def __init__(self, name, age):
[Link] = name
[Link] = age
def display(self):
print(f"Name: {[Link]}, Age: {[Link]}")

class Student(Person): # Child class

[Link] College of Commerce (Autonomous), Vijayapur BCA


Programme
UNIT 3 EXCEPTIONS AND OBJECT ORIENTED PROGRAMMING 15

def __init__(self, name, age, rollno):


super().__init__(name, age) # call parent constructor
[Link] = rollno
def display_student(self):
print(f"Name: {[Link]}, Age: {[Link]}, Roll No: {[Link]}")
# Creating object of Student
s1 = Student("Alice", 20, 101)
[Link]() # Inherited from Person #Name: Alice, Age: 20
s1.display_student() # Defined in Student #Name: Alice, Age: 20, Roll No:
101

[Link] College of Commerce (Autonomous), Vijayapur BCA


Programme

You might also like