0% found this document useful (0 votes)
4 views6 pages

TRY and EXCEPT

Exception handling

Uploaded by

Raja shree
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)
4 views6 pages

TRY and EXCEPT

Exception handling

Uploaded by

Raja shree
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/ 6

TRY and EXCEPT Exception Handling Example Program

class InsufficientBalance(Exception):

def __init__(self, balance):

self.balance = balance

super().__init__(f"Insufficient balance: {balance}")

class BankAccount:

def __init__(self, balance):

self.balance = balance

def withdraw(self, amount):

if amount > self.balance:

raise InsufficientBalance(self.balance)

else:

self.balance -= amount

print(f"Withdrawal successful! New balance: {self.balance}")

# Example usage

account = BankAccount(100)

try:

account.withdraw(150)

except InsufficientBalance as e:

print(e) # Will print the error message with the current balance

1. class InsufficientBalance(Exception):
o Here, you are defining a custom exception called InsufficientBalance.
This class inherits from Python's built-in Exception class, which allows your
new class to function like a typical exception in Python (e.g., you can raise
and catch this exception).
2. def __init__(self, balance):
o The __init__ method is the constructor for the InsufficientBalance class.
It is called when an instance of this exception is created.
o balance is an argument passed to the constructor. This is expected to be the
value of the balance (for example, the remaining money in an account) that
will trigger the exception.
3. self.balance = balance
o Inside the constructor, the balance passed as an argument is saved as an
instance variable self.balance. This allows you to store the balance value
when the exception is raised, so you can later use it in the error message or
handle it accordingly.
4. super().__init__("Insufficient balance: {balance}")
o The super().__init__() calls the constructor of the parent class
(Exception), passing the error message string to it.
o Here, there's a mistake in the string formatting. The message "Insufficient
balance: {balance}" will not substitute the actual balance value in the
string. Instead, the literal text {balance} will be printed as part of the
message.

The correct way to include the balance in the error message is by using an f-string
or format method for string interpolation. For instance:

python
Copy code
super().__init__(f"Insufficient balance: {balance}")

This would replace {balance} with the actual value of the balance.

MULTIPLE EXCEPTIONS HANDLING

In Python, you can handle multiple exceptions in various ways, allowing your program to be
more robust and manage different types of errors effectively. Here are several techniques for
handling multiple exceptions:

1. Using Multiple except Clauses

You can handle different types of exceptions by specifying multiple except blocks. Each
except block is designed to handle a specific exception.

try:
# some code that may raise an exception
x = 1 / 0 # Division by zero
except ZeroDivisionError:
print("Cannot divide by zero.")
except ValueError:
print("Invalid value.")
except TypeError:
print("Type error occurred.")

In this example, the first exception (ZeroDivisionError) is caught and handled, and the
others are ignored.

2. Catching Multiple Exceptions in One except Block


You can specify multiple exceptions in a single except block by providing a tuple of
exception types. This allows for more concise code when you want to handle several
exceptions in the same way.

try:
# some code that may raise an exception
value = int("hello") # ValueError
except (ZeroDivisionError, ValueError, TypeError) as e:
print(f"An error occurred: {e}")

Here, ValueError, ZeroDivisionError, and TypeError are all caught by the same block.

3. Using else and finally with Multiple Exceptions

You can also combine try, except, else, and finally blocks for more advanced exception
handling:

 The else block will run if no exception occurs.


 The finally block will always run, regardless of whether an exception occurred or
not.

try:
# some code that may raise an exception
x = 10 / 2 # No exception
except (ZeroDivisionError, ValueError) as e:
print(f"An error occurred: {e}")
else:
print("No exceptions occurred.")
finally:
print("This will always be executed.")

4. Handling Custom Exceptions

You can create and catch custom exceptions as well. This is useful if you want to handle
specific errors in your application.

class CustomError(Exception):
pass

try:
raise CustomError("Something went wrong.")
except CustomError as e:
print(f"Custom error caught: {e}")
except Exception as e:
print(f"An unexpected error occurred: {e}")

In this case, a CustomError is raised and caught in the except block.

5. Handling Multiple Exceptions in a Hierarchical Manner

Python exceptions have a hierarchy. More specific exceptions are subclasses of more general
ones. You can handle them in a hierarchy, starting from the most specific to the most general
exception.
try:
# some code that may raise an exception
x = "hello" + 10 # TypeError
except TypeError:
print("TypeError: You cannot add a string and an integer.")
except Exception as e: # A more general exception handler
print(f"Some other exception occurred: {e}")

In this example, TypeError is caught first, and if any other error occurs, it’s caught by the
generic Exception handler.

6. Using as for Exception Objects

When catching exceptions, you can access the exception object to get more details about it.
This is useful for logging or debugging.

try:
# some code that may raise an exception
x = int("abc") # ValueError
except ValueError as e:
print(f"A ValueError occurred: {e}")

In this case, the exception message associated with the ValueError is captured in e and
printed.

Conclusion

These methods allow you to manage multiple exceptions in Python efficiently, ensuring that
your program behaves as expected under various error conditions. Whether you want to
handle each error separately, catch multiple exceptions together, or create custom exceptions,
Python provides flexible options for robust error handling.

# Example program demonstrating multiple exceptions handling in Python

def perform_operations():
try:
# Prompt user to input two numbers
num1 = int(input("Enter the first number: "))
num2 = int(input("Enter the second number: "))

# Attempt division (could raise ZeroDivisionError)


result = num1 / num2
print(f"The result of {num1} / {num2} is {result}")

# Attempt to access an invalid index (could raise IndexError)


my_list = [1, 2, 3]
print(f"Accessing the element at index 5: {my_list[5]}")

except ZeroDivisionError as e:
print(f"Error: Cannot divide by zero. {e}")
except ValueError as e:
print(f"Error: Invalid input. Please enter valid integers. {e}")
except IndexError as e:
print(f"Error: List index out of range. {e}")
except Exception as e:
# Catching any other unexpected exceptions
print(f"An unexpected error occurred: {e}")
else:
print("Operation was successful!")
finally:
print("Execution of the try-except block is complete.")

# Call the function to run the program


perform_operations()

Explanation of the Program:

1. User Input: The program prompts the user to input two numbers.
2. Division Operation: It attempts to divide the first number by the second.
3. List Access: It tries to access an element from a list at an invalid index (this will raise
an IndexError).
4. Multiple except Blocks: The program has different except blocks to catch specific
exceptions:
o ZeroDivisionError: Catches division by zero.
o ValueError: Catches invalid input (if the user enters a non-integer).
o IndexError: Catches invalid list index access.
5. else Block: If no exception occurs, it prints a success message.
6. finally Block: This block runs no matter what, ensuring that the program concludes
cleanly.

Sample Output 1 (with valid inputs):


sql
Copy code
Enter the first number: 10
Enter the second number: 5
The result of 10 / 5 is 2.0
Accessing the element at index 5: Error: List index out of range. list
index out of range
Execution of the try-except block is complete.

Sample Output 2 (with invalid input):


python
Copy code
Enter the first number: 10
Enter the second number: hello
Error: Invalid input. Please enter valid integers. invalid literal for
int() with base 10: 'hello'
Execution of the try-except block is complete.

Sample Output 3 (with division by zero):


vbnet
Copy code
Enter the first number: 10
Enter the second number: 0
Error: Cannot divide by zero. division by zero
Execution of the try-except block is complete.

This program shows how Python handles different types of exceptions using multiple except
blocks and how you can cleanly manage errors with else and finally.

You might also like