0% found this document useful (0 votes)
1 views4 pages

Exception

The document explains exceptions in Python, which are events that disrupt the normal flow of a program, often indicating errors such as invalid input or division by zero. It covers common exceptions, how to handle them using try-except blocks, and the use of else and finally clauses for additional control flow. Additionally, it discusses raising exceptions manually and creating custom exceptions for more specific error handling.

Uploaded by

rj0110865
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)
1 views4 pages

Exception

The document explains exceptions in Python, which are events that disrupt the normal flow of a program, often indicating errors such as invalid input or division by zero. It covers common exceptions, how to handle them using try-except blocks, and the use of else and finally clauses for additional control flow. Additionally, it discusses raising exceptions manually and creating custom exceptions for more specific error handling.

Uploaded by

rj0110865
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/ 4

In Python, exceptions are events that occur during the execution of a program that disrupt its normal

flow. These events usually indicate that an error has occurred, such as invalid input, division by zero,
or accessing a non-existent file.

Python provides a robust mechanism to handle these errors gracefully through the use of exceptions,
which allows developers to manage errors without crashing the program.

1 What is an Exception?

An exception is an error detected during execution. It is represented by an exception object in


Python.

2. Common Exceptions

Python includes built-in exceptions such as:

 ValueError: Raised when an operation or function receives an argument of the correct type
but inappropriate value.

 TypeError: Raised when an operation is applied to an object of inappropriate type.

 ZeroDivisionError: Raised when dividing by zero.

 FileNotFoundError: Raised when a file or directory is requested but does not exist.

 IndexError: Raised when accessing a list index out of range.

3. Handling Exceptions

To handle exceptions, Python uses a try-except block. This prevents the program from crashing and
allows for alternative actions to be taken.

Example:

try:

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

result = 10 / number

print("Result:", result)

except ZeroDivisionError:

print("You cannot divide by zero!")

except ValueError:

print("Please enter a valid integer!")

Explanation:

1. Purpose: This program demonstrates how to handle multiple exceptions in Python.

2. Details:
o The try block contains code that might raise an exception.

o int(input(...)): If the user enters a non-numeric value, it raises a ValueError.

o 10 / number: If the user enters 0, it raises a ZeroDivisionError.

o If either exception occurs, the appropriate except block handles it.

3. Example Run:

o Input: 0

 Output: You cannot divide by zero!

o Input: abc

 Output: Please enter a valid integer!

The else Clause

 The else block executes if no exception is raised.

try:

result = 10 / 2

except ZeroDivisionError:

print("Cannot divide by zero!")

else:

print("Division successful:", result)

Explanation:

1. Purpose: This program shows the use of the else clause.

2. Details:

o The try block executes successfully because 10 / 2 does not raise an exception.

o The else block runs if no exception is raised.

o If a ZeroDivisionError had occurred, the else block would not execute.

3. Example Run:

o Output: Division successful: 5.0

The finally Clause

 The finally block is always executed, regardless of whether an exception occurs or not. It is
typically used for cleanup tasks.
try:

file = open("example.txt", "r")

print(file.read())

except FileNotFoundError:

print("File not found!")

finally:

print("Execution completed.")

Explanation:

1. Purpose: This program demonstrates the finally clause, which executes no matter what
happens.

2. Details:

o The try block attempts to open and read a file named example.txt.

o If the file does not exist, a FileNotFoundError is raised and handled by the except
block.

o The finally block runs regardless of whether an exception occurred. It is often used
for cleanup (e.g., closing files).

3. Example Run:

o If the file exists:

 Output: The file content is displayed, followed by Execution completed.

o If the file does not exist:

Raising Exceptions

we can raise exceptions manually using the raise keyword.

age = -1

if age < 0:

raise ValueError("Age cannot be negative!")

Explanation:

1. Purpose: This program demonstrates how to manually raise an exception.

2. Details:

o If the variable age is negative, the raise keyword is used to throw a ValueError with a
custom error message.
o This stops the program unless the exception is caught elsewhere.

3. Example Run:

o Output: ValueError: Age cannot be negative!

Custom Exceptions

Python allows you to define custom exceptions by creating a new exception class that inherits from
the Exception base class.

class CustomError(Exception):

pass

try:

raise CustomError("This is a custom error!")

except CustomError as e:

print(e)

Explanation:

1. Purpose: This program demonstrates how to create and use custom exceptions.

2. Details:

o A new exception class CustomError is created by inheriting from the Exception base
class.

o The try block explicitly raises a CustomError with a custom message.

o The except block catches this specific exception and prints its message.

3. Example Run:

o Output: This is a custom error!

Summary

 Exceptions allow programs to respond gracefully to errors.

 The try-except block is used to handle exceptions.

 Use else for code that should execute only if no exceptions occur.

 Use finally for cleanup actions that must always be executed.

 Custom exceptions can make your error handling more specific and meaningful.

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy