简体   繁体   中英

How to raise exception inside an exception without the traceback?

I am trying to raise an exception inside the exception, without getting an error message of the outer exception and the traceback and print the hey only. However, I am a quite stuck here if I put a string instead of k or m. Any ideas?

The output, which I would need without the traceback

def division(k, m):
   try:
       k / m
   except TypeError:
       raise ValueError ('hey') from None
   return k / m

I'm not exactly sure what you are trying to achieve here, but why don't you just print the string "hey" when the TypeError is raised? Like this:

def division(k, m):
   try:
       k / m
   except TypeError:
       print("hey")
       return None
   return k / m

If you need to raise the ValueError for any reason, then you can catch the ValueError where you call the method, I guess:

def division(k, m):
   try:
       k / m
   except TypeError:
       raise ValueError
   return k / m

try:
    division("not_an_int", "could_be_an_int")
except ValueError:
    print("hey")

From what I understand, You want a custom exception with a custom message format.

class CustomException(Exception):
    def __init__(self, message):
        self.message = message # You can also set it by default so you don't need to input any message
        super().__init__(self.message)

    def __eq__(self, other):
        return self.message == other.message

    def __str__(self):
        return f'{self.message}' # In your case, just to display message.
        # return f'Error message: {self.message}'

def division(k, m):
   try:
       k / m
   except TypeError:
       raise CustomException(message="hey")
   return k / m

try:
    division("not_an_int", "could_be_an_int")
except ValueError as e:
    print(e)

It is not entirely clear what you are trying to achieve here. You don't get the error message because you raise the exception but because you don't catch it again. If you don't want the error message, you need to catch the exception. Then, if you just want to print the message 'hey' you can get it from the exception args.

try:
    division('a', 2)
except ValueError as e:
    print(e.args[0])

The raise ... from None already got rid of the first exception, so you are only seeing the ValueError you raise in the except block in division , but if an exception makes it all the way out to the command line, you have to be informed somehow, and Python will do so by printing the error message.

Now, you can change the default behaviour for uncaught exceptions if you want to. This, for example, will print the args[0] for all exceptions you do not explicitly catch.

import sys
def handle_exception(exc_type, exc_value, exc_traceback):
    print('handler:', exc_value.args[0])
sys.excepthook = handle_exception

The sys.excepthook is a function Python will call for an uncaught exception. So if you do

try:
    division('a', 2)
except ValueError as e:
    print('caught:', e)

division('a', 2)  # not caught

the first division exception is caught, and the handler isn't invoked, and the second isn't caught and the handler is used (and will just print the message 'hey').

It is not really a great idea to change the way all uncaught exceptions are handled, though. You probably want to handle only your own and use the default behaviour for anything else.

But, as I said, it is not entirely clear to me what you are trying to achieve, so all of the above might be entirely unrelated to the question.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM