I'm trying to make a library for python and I want to add custom exceptions, but every time I raise
an exception, the exception shows my raise
as the problem.
For example:
Traceback (most recent call last):
File "c:\Users\james\Desktop\mylibrary\testing.py", line 16, in <module>
'the library user doing absolute shit'
File "c:\Users\james\Desktop\mylibrary\mylibrary\__init__.py", line 100, in function_name
else: raise errors.myerror('Text about my custom error')
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
errors.myerror: Text about my custom error
I manage to solve this problem using sys.excepthook
and no VSCode debugger (Run Without Debugging
):
Traceback (most recent call last):
File "c:\Users\james\Desktop\mylibrary\testing.py", line 16, in <module>
'the library user doing absolute shit'
errors.myerror: Text about my custom error
But when i use the VSCode debugging tool (Start Debugging
) it say again that the problem come from my raise
.
It seems the issue is because you are not handling your custom exception correctly. You have not provided your code to raise the error, but here's what a custom exception needs:
try
statement. The code itself can be in a function, but when the code is run it must be happening inside of a try
block.except
statement to handle the error. This is required with any try
block and if you don't handle your error correctly, there's no point in having a custom exception.Here's an example of a custom exception (here's a guide/example on custom exceptions).
class errors:
class cost_error(Exception):
def __init__(self, message):
super().__init__(message)
self.message = message
money, cost_of_item = 5, 100 #variables for example
try:
if cost_of_item > money:
raise errors.cost_error("This item is too expensive!")
else:
print("Item purchased!")
except errors.cost_error as error:
print(f"Error: {error}")
quit() #This built-in function will terminate the program
print("Hey, if the item is too expensive then this won't print")
As you can see, the error raising happens inside of a try
except
block. This is because when an error is raised, if it is not inside of a try
block it will return your raise statement as an error. If you don't put it into a try
block, it will not be handled and will cause your program to stop.
Example error raised when not using try
block:
Traceback (most recent call last):
File "/Users/person/test.py", line 20, in <module>
raise errors.cost_error("This item is too expensive!")
__main__.cost_error: This item is too expensive!
However, if you just just put it in a try
block but don't handle it, then it'll just ignore the error because that's how the try
except
block's behavior works. Because of this, you need to handle errors.myerror
as an exception in the try
block.