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

Exception Handling

The document provides an overview of errors and exception handling in Python, detailing the types of errors such as syntax errors and exceptions. It explains the importance of exception handling to prevent program crashes and improve user experience, along with examples of built-in and user-defined exceptions. Additionally, it covers the use of try-except blocks, raising exceptions, and the roles of else and finally clauses in exception handling.

Uploaded by

drive3.vaibhav
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 views8 pages

Exception Handling

The document provides an overview of errors and exception handling in Python, detailing the types of errors such as syntax errors and exceptions. It explains the importance of exception handling to prevent program crashes and improve user experience, along with examples of built-in and user-defined exceptions. Additionally, it covers the use of try-except blocks, raising exceptions, and the roles of else and finally clauses in exception handling.

Uploaded by

drive3.vaibhav
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
You are on page 1/ 8

Python – Errors and Exception Handling (Class 12 Notes)

1. What is an Error?

An error is a problem in a program that causes it to stop or behave unexpectedly.


Python errors are of two main types:

Types of Errors:

1. Syntax Errors

2. Exceptions (Runtime Errors)

2. Syntax Errors

• Errors in the structure of the code (spelling, missing colons, brackets, etc.).

• Python stops before running the program.

Example:

print("Hello" # missing closing bracket

Output:

SyntaxError: unexpected EOF while parsing

3. Exceptions (Runtime Errors)

• Errors that occur after the code starts running.

• Happen due to invalid actions like dividing by zero or using wrong data types.

Example:

a=5/0

Output:

ZeroDivisionError: division by zero


4. Difference Between Syntax Error and Exception

Syntax Error Exception

Mistake in writing code Mistake during program execution

Detected before code runs Detected while code is running

Must be corrected to run the code Can be handled using try-except

5. Types of Exceptions

Built-in Exceptions in Python

These are errors that Python already knows about.

Exception Description Example

ZeroDivisionError Division by 0 10 / 0

ValueError Invalid value int("abc")

TypeError Wrong data type 5 + "hello"

IndexError Invalid list index a = [1]; a[2]

KeyError Dictionary key not found d = {}; print(d['x'])

FileNotFoundError File doesn’t exist open("no.txt")

NameError Using variable not defined print(x) if x is not defined


User-Defined Exceptions

You can create your own exceptions by defining a class that inherits from Python's Exception
class.

Example 1:

class NegativeNumberError(Exception):

pass

number = -5

if number < 0:

raise NegativeNumberError("Negative numbers not allowed")

Example 2:

python

CopyEdit

class TooShortError(Exception):

pass

name = "Al"

if len(name) < 3:

raise TooShortError("Name must be at least 3 letters")

6. Why Do We Need Exception Handling?

Without Handling:

• Code stops when error occurs

• Crashes the program

• Users get confused

With Handling:
• Prevents program from crashing

• Friendly error messages

• Continues program flow safely

7. Throwing and Catching Exceptions

Throwing an Exception

Use the raise statement to throw an exception.

Example:

python

CopyEdit

age = -1

if age < 0:

raise ValueError("Age cannot be negative")

Catching an Exception

Use the try-except block to catch and handle errors.

8. Raising Exceptions

a. raise Statement

Used to manually create (raise) an exception.

Example:

python

CopyEdit

marks = -50

if marks < 0:

raise ValueError("Marks cannot be negative")


b. assert Statement

Used to check if a condition is true. If false, it raises an AssertionError.

Example:

python

CopyEdit

age = -3

assert age >= 0, "Age cannot be negative"

9. Handling Exceptions

Python uses the try-except block to catch and fix errors without crashing.

10. Catching Exceptions

Syntax:

python

CopyEdit

try:

# risky code

except ExceptionType:

# handle the error

Example:

python

CopyEdit

try:

x = int(input("Enter a number: "))

print(10 / x)
except ZeroDivisionError:

print("You can't divide by zero!")

11. try-except-else Clause

• else runs only if no error occurred in try.

Example:

python

CopyEdit

try:

x = int(input("Enter a number: "))

except ValueError:

print("Invalid input!")

else:

print("You entered:", x)

12. try-finally Clause

• finally block always runs, whether error occurs or not.

• Used for closing files, cleaning memory, etc.

Example:

python

CopyEdit

try:

f = open("data.txt", "r")

print(f.read())

except FileNotFoundError:

print("File not found.")


finally:

print("This block runs no matter what.")

13. Final Summary

Term Use

try Wrap code that may cause error

except Handle the error

else Runs if no error occurs

finally Always runs (cleanup)

raise Manually raise an error

assert Raise error if condition is false

Exception class Base class for user-defined exceptions

Final Combined Example:

python

CopyEdit

class AgeError(Exception):

pass

try:

age = int(input("Enter your age: "))

assert age > 0, "Age must be positive"

if age < 18:

raise AgeError("You must be 18 or older.")

except ValueError:
print("Please enter a valid number!")

except AssertionError as e:

print("Assertion Error:", e)

except AgeError as e:

print("Custom Error:", e)

else:

print("Age is valid.")

finally:

print("Thank you for using the program.")

You might also like