Error Handling in Go - error-handling

I have a go code like this,
main()
{
do something
do something
.
.
.
do something
}
Now, I don't know which "do something" is throwing an error. Is it possible in Go to catch the error and print it? How?

Go language did not include exception handling mechanism. However, it has panic/recover mechanism which gives a little bit of exception handling.

You probably want recover. Alternatively, check the return values from those functions. It's idiomatic in go to call the error value ok, and immediately check it.
meh, ok := do_something()
if !ok {

Related

Will it throw an exception if it is null?

I am pretty new Kotlin world and do not understand the following code snippet:
#GET
#Path("/env/{id}")
fun read(#PathParam("id") id: EnvStageId): Uni<Environment> =
createUni(repo.read(id)).map {
it ?: throw WebApplicationException(Response.status(Response.Status.BAD_REQUEST)
.type(TEXT_PLAIN)
.entity("Environment $id does not exist")
.build())
}
The question is, if it is null it will then throw an exception right?
The elvis operator ?: is not null or the continuation.
Yes. If it is null then it will throw an exception.
The thing is, sometimes it is better to crash: if that operation is supposed to always return something from the local db, then if it fails you get an alert that there is something very bad going on, crashalytica for prod are standard this days.
Maybe the design is exceptions throwing exceptions on low level implementations. I do not think so, because that seems to be mixing network with repository, so I will doubt it. But on the other hand it seems to be so, because someone wrote an special exception for that, if it so, then the next architecture layer should catch those exceptions and handle them gracefully.

How do I find out about possible error values of Go standard library functions?

When calling a Go function that returns an error, I wonder how to deal with a non-nil error value. I can just abort, log it, or pass it to the caller. Or a combination thereof. But it would be better if I found out what went wrong and reacted in a more fine-grained manner.
Thus, how can I find out about possible error values and their meanings? For example, I want to use the http.NewRequest function. Look it up in the docs. There, it only says that there are possible error conditions but not which ones. How can I find out about these?
First off, if you haven't read it yet, I recommend reading this blog article about error handling in Go, it might clarify some things for you.
As for finding out the possible error values of Go stdlib functions, if it's not explicitly documented, one option is to go read the code. For example, on the http.NewRequest function, you can click on the header, which takes you to the source code. There you can see that right now, it only returns an error in one case, when the URL parsing fails. Exploring the url.Parse function, you'll see that it may return url.Error, which you can check for with a type assertion:
package main
import (
"log"
"net/http"
"net/url"
)
func main() {
r, err := http.NewRequest("GET", "http://[fe80::%31%25en0]:8080/", nil)
if perr, ok := err.(*url.Error); ok && perr != nil {
log.Fatal("Parse error, check URL formatting: ", perr)
} else if err != nil {
log.Fatal("Error creating HTTP request")
}
// ... success case
log.Println(r)
}
Running this gives you the parse error, which you may or may not want to handle differently in your application:
2009/11/10 23:00:00 Parse error, check URL formatting: parse http://[fe80::%31%25en0]:8080/: percent-encoded characters in host
I agree with JimB's comment however, specifically checking the type of error in this case is probably not a useful thing to do. In 99.99% of cases all you need to know is that creating the request failed (err != nil) and handle that eventuality in an appropriate way (logging, returning, etc).

Ignoring Exceptions in Object Oriented Programming

In some applications, I came across some lines of code which deliberately eats the exceptions. In my application the benefit of doing this is - To ignore the exception and just continue with the loop(The exception handled is for an error thrown inside the loop). The following lines of code looks evil to even an experienced developers. But is sensible to the context(I mean, that is the requirement - to process all the files in the directory).
try{
//some lines of code which might throw exception
}catch(Exception e){
//no code to handle the error thrown
}
What other benefits can ignoring exceptions provide?
If it is a requirement to process all the files, if you get an exception during processing one of them, is not the requirement broken already? Either something failed or the exception is not needed.
If you want to continue the processing handle the exception, then continue. Why not just report the problem with processing a given file,so someone can later process it manually? Probably even stupid cerr << "Hey I had trouble with this file '" << file <<', so I skipped it.\n" would be better than nothing.
Exception is there to signal something. If you are ignoring it either you are doing something nasty, or the exception is not needed.
The only valid reason for ignoring the exception I can think of is when someone throws exceptions at you for no good reason. Then maybe, yeah, ignore.
This is generally the mark of bad code - you always want to handle your exceptions by at a minimum reporting what the exception is. Ignoring exceptions will let your program keep running, but generally exceptions are thrown for a reason and you or the user need to know what that reason is. Doing a catch-all and escaping just means the coder was too lazy to fix whatever problems cropped up.
The exception is if the coder is throwing exceptions merely to pass arguments, which is something I saw on DailyWTF once.
Usually we should not absorb the exception but there can be reason like there is a function which is out of business logic that is just to help some kind of extra functionality, then you do not want your application to break if that function throw the exception in that case you absorb/eat the exception. But I do not recommend the empty catch block, one should log this in ELMAH or other error logging tools for future.
I don't think there any any benefits of ignoring exceptions. It will only cause problems. If you want the code to be executed in the loop, after handling it, it will continue with the loop because exception is handled. You can always process the files in your directory even if you are not doing anything after handling exceptions.
It will be better if you write some log regarding the files for which exception is thrown
If you eat the exception. You may never know what is the actual cause of the problem.
Considerr this example
public class Test {
private int x;
public void someMethod(){
try {
x = 10/0;
} catch (Exception e) {
}
}
public static void main(String[] args) {
Test test = new Test();
test.someMethod();
System.out.println(test.x);
}
}
This will print simply 0 the default value of x as exception occured during division and value was not assigned to x
Here you are supposed to get actual result of the division. Well it will definitely throw an ArithMeticException because we are dividing by zero and we have not written anything in catch block. So if the exception occurs, nothing will be printed and value of x will be 0 always and we can't know whether the division is happend or not. So always handle exceptions properly.

How to return often occurring error in object oriented environment?

assume you have a function that polls some kind of queue and blocks for a certain amount of time. If this time has passed without something showing up on the queue, some indication of the timeout should be delivered to the caller, otherwise the something that showed up should be returned.
Now you could write something like:
class Queue
{
Thing GetThing();
}
and throw an exception in case of a timeout. Or you
write
class Queue
{
int GetThing(Thing& t);
}
and return an error code for success and timeout.
However, drawback of solution 1 is that the on a not so busy queue timeout is not an exceptional case, but rather common. And solution 2 uses return values for errors and ugly syntax, since you can end up with a Thing that contains nothing.
Is there another (smart) solution for that problem? What is the preferred solution in an object oriented environment?
I would use exceptions only when the error is serious enough to stop the execution of the application, or of any big-enough application's component. But I wouldn't use exceptions for common cases, after which we continue the normal execution or execute the same function again. This would be just using exceptions for flow control, which is wrong.
So, I suggest you to either use the second solution that you proposed, or to do the following:
class Queue
{
bool GetThing(Thing& t); // true on success, false on failure
string GetLastError();
};
Of course you can stick with an int for an error code, instead of a string for the full error message. Or even better, just define class Error and have GetLastError() return it.
Why not just return null from GetThing in your first solution, changing it to return a Thing *? It seems to fit the bill, at least from the information you've given so far.
In the first, and second case, you can't do anything but throw an exception. When you return a Thing, or a Thing&, you don't have the option of not returning a Thing.
If you want to fail without using an exception then you need:
class Queue
{
// Either something like this. GetThing retuns NULL on an error,
// GetError returns a specific error code
Thing* GetThing();
int GetError();
// This kind of pattern is common. Return a result code
// and set ppOut to a valid thing or NULL.
int GetThing(Thing** ppOut);
};

Proper use of try .. catch

Should I be using this method of throwing errors:
if (isset($this->dbfields[$var])) {
return $this->dbfields[$var];
} else {
throw new FieldNotFoundException($var);
}
or this style:
try {
return $this->dbfields[$var];
} catch (Exception $e) {
throw new FieldNotFoundException($var);
}
...or something else altogether?
quick explanation of the code: $this->dbfields is an array. isset() checks if a variable is set, in this case, whether the array element exists.
The second example is bad. You're taking a lot of overhead to catch an exception when, as you demonstrate, it's just as easy to prevent the exception in the first place. Plus you also assume you know why that exception was thrown - if there was some other exception, like say an out of memory or something, you're reporting it as a "field not found" even if it wasn't.
Keep in mind that try/catch in languages like C++ and Java are very expensive because of all the state they have to save and restore. Python, on the other hand, has very cheap exceptions and they positively encourage you to use a try/except for simple validation. But even so, catching everything and pretending it's one type of exception is still bad.
//First let's do the checks.
if(!isset($this->dbfields[$var]))
throw new FieldNotFoundException($var);
//Now we're in the clear!
return $this->dbfields[$var];
Catching "Exception" is not, most of the time, considered a good practice, out of the two you displayed, I would use option 1.
Catching all exceptions may hide a different exception and mask it as a FileNotFoundException.
I prefer the first one, but if dbfields[$var] throws something reasonable when you access a non-existent element, then I'd prefer just returning it without checking.
I don't particularly like changing the exception type unless I have a good reason -- also if you do, make sure to try to preserve the original exception and stack trace.
Just re-read your explanation.
I guess your method there in #1 is going to catch any exceptions that might be thrown and simply return a bool. I definitely don't like the catching of the generic exception most of the time, so #2 wouldn't be my choice.
"...or something else altogether?"
Neither is very good, so something else would be appropriate.
Fix version 2 to catch the correct exception, not every possible exception. Post that as option 3. I'll upvote something that catches a specific exception instead of Exception.
This is far from language-agnostic.
Some languages won't throw errors for accessing non-existant fields, and the preferred pattern depends a lot on the implementations of the arrays, tables, objects, etc.