Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the best way to return error message from function?

Tags:

c#

.net

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";
like image 465
Raed Alsaleh Avatar asked Apr 08 '13 07:04

Raed Alsaleh


People also ask

How do you return an error in a Python function?

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.

How do you return an error in JavaScript?

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.

How do you return an error in C++?

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.

What does raise exception return?

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.


1 Answers

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:

  • You can ignore invalid error code returned from your funcion and this could lead you to the situation where your system state is corrupted whereas Exception is something you can't ignore.
  • If your funcion does something usable then it should return some data you interested in and not the error codes, this gives you more solid design.
like image 157
Denys Denysenko Avatar answered Sep 20 '22 17:09

Denys Denysenko