Proper use of try .. catch - error-handling

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.

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 to find what exception some library code might throw

I am new to Kotlin and I have the following problem: In my project I am using a small library (JAR, no sources). In it there are few custom exception classes defined which inherit Exception class. Some methods throw these exceptions.
In my code I bump into the problem that I don't know what exception the library code might throw so I can catch it and thus sometimes the exception goes trough the roof.
What it is the usual way to handle such situations in Kotlin?
Normaly such exceptions should be declared in the documentation of the library that you are using (either the JavaDoc, KDoc, or a website). There is no structured way to get all exceptions a function can throw, other than decompiling the code and step through it yourself. (by using the build in decompiler, that jet brains ship in IntelliJ for example)
You could also catch all exceptions, but I would always argue, that this is not a good decision in almost all cases.
I don't exactly know the right approach in kotlin, but you may use the following idea from scala:
Try -
try Success(r) catch {
case NonFatal(e) => Failure(e)
}
If exception is not fatal:
case _: VirtualMachineError | _: ThreadDeath | _: InterruptedException | _: LinkageError | _: ControlThrowable => false
case _ => true
then just return Failure(e) otherwise throw it.
How can you use it? At least you will not end up like this:
try {
...
} catch {
case _ : Throwable => ... // catch all exceptions
}
Yes, you still don't know which exceptions code may throw, but using this approach you can control the general execution flow.
But of course, it will be much better if docs list exceptions which may be thrown.

VB.NET Try/Catch/When - Stay away or does it have its use?

VB.NET has, unlike c#, a feature to conditionally catch exceptions in a Try/Catch/Finally block.
I thought I read somewhere that this is usually bad practice as it encourages people to put (business) logic in the exception handling mecanism and that you essentially end up with a glorified GoTo.
Try
// Do something
Catch ex As MyException When [condition]
//
End Try
So are there legit cases to use the When feature or should we stay away from it?
This has probably already been answered but I was unable to find anything relevant due "When" being a pretty bad keyword for a search.
The usual case I can think of is when you only want to capture a specific exception, based on the content of that exception. E.g.:
Try
// Do something
Catch ex As SqlException When ex.Number = 547
// Constraint Violation
End Try
Which saves you from capturing all SqlExceptions, then examining the Number property, and then having to re-throw the exception if it doesn't match.
See also The good and bad of exception filters:
For instance, if you have a fairly general exception, like COMException, you typically only want to catch that when it represents a certain HRESULT. For instance, you want to let it go unhanded when it represents E_FAIL, but you want to catch it when it represents E_ACCESSDEINED because you have an alternative for that case. Here, this is a perfectly reasonable conditional catch clause:
Catch ex As System.Runtime.InteropServices.COMException When ex.ErrorCode() = &H80070005
The alternative is to place the condition within the catch block, and rethrow the exception if it doesn’t meet your criteria. For instance:
Catch ex As System.Runtime.InteropServices.COMException
If (ex.ErrorCode != &H80070005) Then Throw
Logically, this “catch/rethrow” pattern does the same thing as the filter did, but there is a subtle and important difference. If the exception goes unhandled, then the program state is quite different between the two. In the catch/rethrow case, the unhandled exception will appear to come from the Throw statement within the catch block. There will be no call stack beyond that, and any finally blocks up to the catch clause will have been executed. Both make debugging more difficult. In the filter case, the exception goes unhandled from the point of the original throw, and no program state has been changed by finally clauses.

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);
};