If face a logic error error such (Expired user, invalid ID)
, then what is the best way to tell the parent method of this error from the following :
1- Throwing customized exception like the following :
try
{
//if (ID doesn't match) then
Throw new CustomException(-1,"ID doesn't match");
}
catch(CustomException ex)
{
throw ex
}
catch(Exception ex)
{
throw new CustomException(ex.ErrorCode,ex.message);
}
2- return error message and code like :
//if (ID doesn't match) then
This.ErrorCode= -1;
This.Message= "ID doesn't match";
To return an error from a Python function, don't use dummy values such as return -1 or return None . Instead, use the raise keyword such as raise ValueError('your msg') . The error will “bubble up” the stack until caught by a try/except block.
In JavaScript error message property is used to set or return the error message. Return Value: It returns a string, representing the details of the error.
Since C++ constructors do not have a return type, it is not possible to use return codes. Therefore, the best practice is for constructors to throw an exception to signal failure. The throw statement can be used to throw an C++ exception and exit the constructor code.
Raising an exception terminates the flow of your program, allowing the exception to bubble up the call stack. In the above example, this would let you explicitly handle TypeError later. If TypeError goes unhandled, code execution stops and you'll get an unhandled exception message.
The better way is to throw custom exception. That's why they were introduced. If you need to provide specific info, like ErrorCode
or something else, you could easily extend base Exception
class to do so. Main reasons are:
Exception
is something you can't ignore. If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With