1
#!/usr/bin/env python

#import re


def test_ex1(input):
    if re.match(r'^[A-Z]+$',input):
        print 'Match'
        return True
    print 'No Match'
    return False   


#test_ex1('ABC')
try:
    test_ex1('ABC')
except Exception:
    raise Exception

If I run the above program,it will print following exception message.

a:~/Python> python test.py
Traceback (most recent call last):
  File "test.py", line 18, in <module>
    raise Exception
Exception

What is the right way in Python to make it print the following stack trace while catching exception using try except without changing test_ex1 subroutine?

Traceback (most recent call last):
  File "test.py", line 15, in <module>
    test_ex1('ABC')
  File "test.py", line 8, in test_ex1
    if re.match(r'^[A-Z]+$',input):
NameError: global name 're' is not defined
3
  • Do you want to re-raise the exception? Commented May 23, 2017 at 15:40
  • Have a look at the documentation Commented May 23, 2017 at 15:41
  • How do I print all exceptions recursively without adding a print_exc call in every function within a function? Commented May 23, 2017 at 21:03

2 Answers 2

2

One way is using the traceback module

import traceback

try:
  re.match()
except Exception:
  traceback.print_exc()
Sign up to request clarification or add additional context in comments.

7 Comments

Can I do this without touching test_ex1 subroutine?
@Jean Of course, you don't have to modify it. Try the following: in the except body, just write pass. Nothing will be printed. Now, put traceback.print_exc(). The traceback will be printed. No modification was required.
If you mean that you can just drop this and use test_ex1 inside the try block then yes, you can. On that note, you might want to change the name of the parameter, input is a built-in function in python.
Thanks. Why do I have to import traceback when Python seems to have ability to print stack trace natively?
We import it so we can handle the tracebacks however we want. We need to use import to do that because the python standard library is huge, it's separated in modules so that the compiler doesn't have to load everything in every program.
|
-1

I once used following to print all traceback as:

import sys

try:
    # code here
except Exception:
    print(sys.exc_info()[0])

The raise keyword is being used to throw your error up to the stack and handle at upper level of function call.

2 Comments

This does not answer the question. OP wants to print the traceback.
I edited my answer above. I mis-understood the question. Sorry for that.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.