Customize Tracebacks
Lesson 16 of 16 in Coddy's Exception Handling in Python course.
When you run below program, you will get tracebacks details, Exception and Exception standard message on output window.
print(100 + "hello")Above program will create following output:-
Traceback (most recent call last):
File "<pyshell#0>", line 1, in <module>
print(100+'hello')
TypeError: unsupported operand type(s) for +: 'int' and 'str'First 3 lines are Tracebacks details containing line number, filename, statement etc.
Last line is Exception:standard message for Exception.
When Exception occurs, a call goes to sys.excepthook() function containing below arguments.
- exc_type :- Type of Exception occurred.
- exc_value :- standard message for Exception
- exc_traceback:- Traceback details
sys.excepthook() then prints all these arguments on output window as a standard error.
Challenge
EasyOverride sys.excepthook function to customize and print your own messages on output window if Exception occurs. For above python statement, it should print "Something Went Wrong!" and then Exception standard message only.
Try it yourself
import sys
def my_exception(exc_type, exc_value, exc_traceback):
#your code goes here
#override using assignment
def add(val1, val2):
print(val1+val2)All lessons in Exception Handling in Python
4Customization/best practices
Customize Tracebacks