Home > Mobile >  Raise Exception - Passing a value
Raise Exception - Passing a value

Time:08-04

In order to handle some exceptions I've used a code like this:

try:

    shutdown=SSH_CONNECTION(IP, USER_GW, PSW_GW)
    if shutdown ==1:
        print ('No SSH')
        raise ValueError 

except ValueError:
    print ('print something')

since I call SSH_CONNECTION in several parts of my programm, I'd like to know if it possible to pass a value via the raise command in order to understand where the loss of connection (exception) occurred. For instance I was wondering if it is possible to do something like this:

try:

    shutdown=SSH_CONNECTION(IP, USER_GW, PSW_GW)
    if shutdown ==1:
        print ('No SSH')
        raise ValueError  x=0
        
    shutdown=SSH_CONNECTION(IP, USER_GW, PSW_GW)
    if shutdown ==1:
        print ('No SSH')
        raise ValueError  x=1
        

except ValueError:
    if x=0:
        print ('print something')
    elif x=1
        print ('print something else')
    

CodePudding user response:

You can give arguments to an exception, they will be stored in the args attribute.

try:
    shutdown = SSH_CONNECTION(IP, USER_GW, PSW_GW)
    if shutdown == 1:
        raise ValueError("No SSH", 0)
    shutdown = SSH_CONNECTION(IP, USER_GW, PSW_GW)
    if shutdown == 1:
        raise ValueError("No SSH", 1)
except ValueError as value_error:
    message, code = value_error.args
    print(message)
    if code == 0:
        print("0")
    elif code == 1:
        print("1")
  • Related