The Wayback Machine - https://web.archive.org/web/20240717024400/https://www.geeksforgeeks.org/how-to-pass-argument-to-an-exception-in-python/
Open In App

How to pass argument to an Exception in Python?

Last Updated : 07 Oct, 2021
Improve
Suggest changes
Post a comment
Like Article
Like
Save
Share
Report

There might arise a situation where there is a need for additional information from an exception raised by Python. 
Python has two types of exceptions namely, Built-In Exceptions and User-Defined Exceptions.
Why use Argument in Exceptions? 
Using arguments for Exceptions in Python is useful for the following reasons: 

  • It can be used to gain additional information about the error encountered.
     
  • As contents of an Argument can vary depending upon different types of Exceptions in Python, Variables can be supplied to the Exceptions to capture the essence of the encountered errors. Same error can occur of different causes, Arguments helps us identify the specific cause for an error using the except clause.
     
  • It can also be used to trap multiple exceptions, by using a variable to follow the tuple of Exceptions. 
     

Arguments in Built-in Exceptions:

The below codes demonstrates use of Argument with Built-in Exceptions:
Example 1: 

Python3




try:
    b = float(100 + 50 / 0)
except Exception as Argument:
    print( 'This is the Argument\n', Argument)


Output:  

This is the Argument
 division by zero

Example 2: 

Python3




my_string = "GeeksForGeeks"
 
try:
    b = float(my_string / 20)
except Exception as Argument:
    print( 'This is the Argument\n', Argument)


Output:  

This is the Argument
 unsupported operand type(s) for /: 'str' and 'int'

Arguments in User-defined Exceptions:

The below codes demonstrates use of Argument with User-defined Exceptions:
Example 1: 

Python3




# create user-defined exception 
# derived from super class Exception
class MyError(Exception):
   
    # Constructor or Initializer
    def __init__(self, value):
        self.value = value
   
    # __str__ is to print() the value
    def __str__(self):
        return(repr(self.value))
   
try:
    raise(MyError("Some Error Data"))
   
# Value of Exception is stored in error
except MyError as Argument:
    print('This is the Argument\n', Argument)


Output:  

This is the Argument
 'Some Error Data'

Example 2: 

Python3




# class Error is derived from super class Exception
class Error(Exception):
 
    # Error is derived class for Exception, but
    # Base class for exceptions in this module
    pass
 
class TransitionError(Error):
 
    # Raised when an operation attempts a state
    # transition that's not allowed.
    def __init__(self, prev, nex, msg):
        self.prev = prev
        self.next = nex
 
try:
    raise(TransitionError(2, 3 * 2, "Not Allowed"))
 
# Value of Exception is stored in error
except TransitionError as Argument:
    print('Exception occurred: ', Argument)


Output: 

Exception occurred:  (2, 6, 'Not Allowed')


Similar Reads

How to Fix: SyntaxError: positional argument follows keyword argument in Python
In this article, we will discuss how to fix the syntax error that is positional argument follows keyword argument in Python An argument is a value provided to a function when you call that function. For example, look at the below program - Python Code # function def calculate_square(num): return num * num # call the function result = calculate_squa
3 min read
Pass list as command line argument in Python
The arguments that are given after the name of the program in the command line shell of the operating system are known as Command Line Arguments. Python provides various ways of dealing with these types of arguments. One of them is sys module. sys Module A module is a file containing Python definitions and statements. The sys module provides functi
3 min read
How to pass a list as a command-line argument with argparse?
Argparse is a Python library used to parse command-line arguments in a user-friendly manner. It makes it easy to write user-friendly command-line interfaces, and it is widely used in Python applications. In this tutorial, we will discuss how to pass a list as a command-line argument using the Argparse library in Python. Passing a List as a Command
5 min read
Python | Raising an Exception to Another Exception
Let's consider a situation where we want to raise an exception in response to catching a different exception but want to include information about both exceptions in the traceback. To chain exceptions, use the raise from statement instead of a simple raise statement. This will give you information about both errors. Code #1 : def example(): try: in
2 min read
Passing function as an argument in Python
A function can take multiple arguments, these arguments can be objects, variables(of same or different data types) and functions. Python functions are first class objects. In the example below, a function is assigned to a variable. This assignment doesn’t call the function. It takes the function object referenced by shout and creates a second name
3 min read
Python Lambda with underscore as an argument
In Python, we use the lambda keyword to declare an anonymous function. Lambda function behaves in the same way as regular functions behave that are declared using the 'def' keyword. The following are some of the characteristics of Python lambda functions: A lambda function can take more than one number of arguments, but they contain only a single e
1 min read
Return the Angle of the Complex Argument in Radians in Python using NumPy
In this article, we are going to see how to return the angle of the complex argument in radians in Python Using NumPy. The NumPy library provides the numpy.angle() method to return the angle of the complex argument in radians in python. Let's look at the syntax of the method. Syntax: numpy.angle(z, deg=False) parameters: z: array like object. input
3 min read
Use mutable default value as an argument in Python
Python lets you set default values ​​for its parameters when you define a function or method. If no argument for this parameter is passed to the function while calling it in such situations default value will be used. If the default values ​​are mutable or modifiable (lists, dictionaries, etc.), they can be modified within the function and those mo
5 min read
Specify Argument Type For List of Dictionary For a Python
In this article, we will see how we can specify the argument type for a list of Dictionary for Python. As we know, Python is a dynamically typed language so the data type of a variable can change anytime. If a variable containing an integer may hold a string in the future, which can lead to Runtime Errors, Therefore knowing the data type of the arg
2 min read
Keyword and Positional Argument in Python
Python provides different ways of passing the arguments during the function call from which we will explore keyword-only argument means passing the argument by using the parameter names during the function call.is Types of argumentsKeyword-only argumentPositional-only argumentDifference between the Keyword and Positional ArgumentKeyword-Only Argume
4 min read
Article Tags :
Practice Tags :
three90RightbarBannerImg