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
Jean
  • 21,665
  • 24
  • 69
  • 119

2 Answers2

2

One way is using the traceback module

import traceback

try:
  re.match()
except Exception:
  traceback.print_exc()
Luis Orduz
  • 2,887
  • 1
  • 13
  • 19
  • Can I do this without touching `test_ex1` subroutine? – Jean May 23 '17 at 15:49
  • @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. – Right leg May 23 '17 at 15:54
  • 1
    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. – Luis Orduz May 23 '17 at 15:56
  • Thanks. Why do I have to `import traceback` when Python seems to have ability to print stack trace natively? – Jean May 23 '17 at 15:57
  • 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. – Luis Orduz May 23 '17 at 16:03
  • How do I print the entire stack trace recursively? `print_exc()` only prints one level of stacktrace. – Jean May 23 '17 at 21:01
  • Could you show us your code? It's supposed to print the entire stack. – Luis Orduz May 24 '17 at 01:19
-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.

Right leg
  • 16,080
  • 7
  • 48
  • 81
Sijan Bhandari
  • 2,941
  • 3
  • 23
  • 36