TRY and EXCEPT
TRY and EXCEPT
class InsufficientBalance(Exception):
self.balance = balance
class BankAccount:
self.balance = balance
raise InsufficientBalance(self.balance)
else:
self.balance -= amount
# 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.
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:
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.
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.
You can also combine try, except, else, and finally blocks for more advanced exception
handling:
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.")
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}")
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.
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.
def perform_operations():
try:
# Prompt user to input two numbers
num1 = int(input("Enter the first number: "))
num2 = int(input("Enter the second number: "))
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.")
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.
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.