Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Argument of an Exception in Python
An exception can have an argument, which is a value that provides additional information about the problem. The contents of the argument vary by exception. You capture an exception's argument by supplying a variable in the except clause as follows ?
Syntax
try:
# Your operations here
pass
except ExceptionType as argument:
# You can access the exception argument here
print(argument)
If you write the code to handle a single exception, you can have a variable follow the name of the exception in the except statement using the as keyword. If you are trapping multiple exceptions, you can have a variable follow the tuple of exceptions.
This variable receives the value of the exception, mostly containing the cause of the exception. The variable can receive a single value or multiple values in the form of a tuple. This tuple usually contains the error string, the error number, and an error location.
Example
Following is an example demonstrating how to capture exception arguments ?
# Define a function to convert temperature
def temp_convert(var):
try:
return int(var)
except ValueError as argument:
print("The argument does not contain numbers")
print("Exception details:", argument)
# Call the function with invalid input
temp_convert("xyz")
The argument does not contain numbers Exception details: invalid literal for int() with base 10: 'xyz'
Handling Multiple Exception Types
You can also capture arguments when handling multiple exception types ?
def divide_numbers(a, b):
try:
result = int(a) / int(b)
return result
except (ValueError, ZeroDivisionError) as error:
print(f"Error occurred: {type(error).__name__}")
print(f"Error message: {error}")
# Test with different error scenarios
print("Test 1: Invalid number")
divide_numbers("abc", "2")
print("\nTest 2: Division by zero")
divide_numbers("10", "0")
Test 1: Invalid number Error occurred: ValueError Error message: invalid literal for int() with base 10: 'abc' Test 2: Division by zero Error occurred: ZeroDivisionError Error message: division by zero
Accessing Exception Attributes
Exception objects have various attributes that provide detailed information ?
import sys
def demonstrate_exception_attributes():
try:
# This will raise a FileNotFoundError
with open("nonexistent_file.txt", "r") as file:
content = file.read()
except FileNotFoundError as e:
print(f"Exception type: {type(e).__name__}")
print(f"Exception message: {e}")
print(f"Exception args: {e.args}")
demonstrate_exception_attributes()
Exception type: FileNotFoundError Exception message: [Errno 2] No such file or directory: 'nonexistent_file.txt' Exception args: (2, 'No such file or directory')
Conclusion
Exception arguments provide valuable debugging information about what went wrong in your code. Use the as keyword to capture exception details and access attributes like args for comprehensive error handling.
