How are try/catch blocks implemented? - error-handling

If an exception occurs in a try block, how is execution transferred to the catch block? This is not a C#/Java/C++ question, I'm just wondering how it works internally.

this is not a c#/java/c++ question. How it works internally,how the line knows to go catch statement.
How this works internally makes this pretty much a c#/java/C++ question (because it will be implemented differently).
In Java, a try block installs itself into a special table (in the class file). When the JVM throws an exception, it looks at that table to see where the next catch or finally block to go to is.

When an exception occurs a special instruction is executed (usually called interrupt). This leads to executing a generic error handler that deduces which is the latest installed suitable exception handler. That handler is then executed.

There is a difference how exceptions are technically handled between natively compiled languages such as C++ and languages using byte-code being executed on a virtual machine such as Java or C#.
C++ compilers usually generate code that protocols the information needed for exception handling at runtime. A dedicated data structure is used to remember entrance/exit of try blocks and the associated exception handler. When an exception occurs, an interrupt is generated and control is passed to the OS which in turn inspects the call stack and determines which exception handler to call.
Further details are pretty well explained in the following article by Vishal Kochhar:
How a C++ compiler implements exception handling
In Java or .NET there is no need for the overhead of maintaining exception handling information as the runtime will be able to introspect the byte code to find the relevant exception handler. As a consequence, only exceptions that are actually thrown are causing an overhead.

It is basically parsing fundamentals of the language.
You can get all info at Here

it should work in all langues somewhat like this:
if (error_occured xy while doing things in try){
call_catch_part(error xy)
}

you could do the same in C even though there is no exception handling per se.
There you would use setjmp/longjmp unfortunately you then do not get the stack unwinding and have to handle all the nitty-gritty yourself.

Related

Kotlin - Document exception thrown by an interface method

Since Kotlin hasn't got checked exception, what's the correct way to document exception expected to be thrown by an interface method? Should I document it in the interface or in the implementing class (only if the concrete method actually throws it)?
Since clients program against the interface, I'd suggest the documentation to be made in the Javadoc/KDoc of that interface. Whether you actually should document them is discussed in this thread for example:
Oracle recommends:
If it's so good to document a method's API, including the exceptions it can throw, why not specify runtime exceptions too? Runtime exceptions represent problems that are the result of a programming problem, and as such, the API client code cannot reasonably be expected to recover from them or to handle them in any way. Such problems include arithmetic exceptions, such as dividing by zero; pointer exceptions, such as trying to access an object through a null reference; and indexing exceptions, such as attempting to access an array element through an index that is too large or too small. Runtime exceptions can occur anywhere in a program, and in a typical one they can be very numerous. Having to add runtime exceptions in every method declaration would reduce a program's clarity.
So if the information is useful for a client it should be documented (i.e. if the client can handle it, e.g. IOException). For "regular" runtime exceptions such as an IllegalArgumentException I would say "no", do not document them.

What is the main use of NSAssert Vs. NSException

What is the main use of NSAssert Vs. NSException. What is more recommended and when?
Assertions are generally used during development only and are compiled-out of the app when in release mode (this is controlled by NS_BLOCK_ASSERTIONS). Exceptions, on the other hand, can be used at all times.
When an exception is thrown, it travels back up the call chain, until it is either caught (and reported, ignored, or another exception is thrown) or it reaches the top, in which case it will cause the app to crash. It can be considered part of the contract of a class method and needs to be documented so the caller can handle this correctly.
Assertions are really a runtime developer check that ensure that something (generally a instance variable) is in a certain state and if it's not then abort() in order to bring the issue to the developers attention. It's a developer sanity check to check that something is in the state the developer expects it to be.
Assertions are used to find things that should never happen under any circumstances if your code is working the way you think it should be. If they are happening, there is a bug in your code and you want to know about it, at least if it happens during testing. (Most people turn off assertions in released code.)
In contrast, exceptions are used to find things that have gone wrong over which you have no control. For example, if your application is dependent on a database server and that database server is unavailable, that might raise an exception in your code. (Do not make the mistake of using exceptions for things like user input validation. If it's regular program flow--the user forgot to enter a field or whatever--that's not an exception. Exceptions should be exceptional.)

Why do many languages treat Exception-objects as first-class citizens?

When we get an objects that is actually are exceptions, we can do with them anything that we can do with ordinar objects in our language. We can pass them as an argument, we can store them in some collection and, what is the worst, we can return them as a result from the methods!
So there is a possibility for someone to write smelly code like this:
public Exception doSomethingCritical()
{
Exception error = null;
try
{
...
}
catch (Exception e)
{
// maybe at least here is the logging of the error if we are lucky
error = e;
}
return error;
}
So the question is why is the concept of an Exception-object is a first-class citizen in many OO languages? Maybe it is better if we have only limited constructions in the language that is allowed for exception-objects (like throw).
The problem with treating exceptions as a special case, and allowing only limited functionality with exceptions is that ultimately somewhere every good program needs to do something with exceptions, whether it be a global error-handler or a limited item that appropriately deals with the exception. By making exceptions first class citizens, there are many benefits, such as:
Allowing subclassing of exceptions. This is invaluable for exception handling as code dealing with exceptions can narrow their scope and deal only with exceptions they know how to deal with. I'd go so far as to say that any non-global exception handling routine that is catching just "Exception" is probably doing it wrong.
Passing data along with exceptions. Exceptions aren't very useful if the only thing you know in your catch logic is that an exception occurred. Stack traces, messages and even custom data for certain exception types are invaluable in identifying and resolving the problem that caused the exception.
Creating error handling routines that use OOP themselves. If exceptions couldn't be passed as objects, you couldn't for instance have a library that deals with exceptions - well, at least not a well written one.
Besides all of that, there's no way to guard against bad exception handling like you posted above. Even if an exception wasn't a first class citizen, there's no way to stop a developer from eating any and all exceptions and carrying on their merry way (at least, without fundamentally breaking how we think of exceptions)
My opinion.
I think you are confusing two different things: the Exception and the Exception throwing.
The exception throwing is an out-of-band process that allows you to throw an object through a preferential, lateral channel. This object can be intercepted and handled through the Exception catching mechanism.
The Exception is just one object that you can (preferentially) throw via the Exception throwing out-of-band channel. Of course, this channel can have requisites for the interface of the object being thrown, requisites that are satisfied by the Exception class interface.
You are looking at the issue the other way around. Indeed you can do horrors, but there's nothing special about the Exception object, apart of being the preferred object that is thrown in the out-of-band channel.
I've never actually seen that example you've used. And I can't see how not allowing people to return exceptions will make a big difference to conceptually poor code - compare
public int doSomethingCritical()
{
int error = 0;
try
{
...
}
catch (Exception e)
{
// maybe at least here is the logging of the error if we are lucky
error = E_SOMETHINGBAD;
}
return error;
}
Whereas if you create a new kind of "thing" to be used for exceptions that isn't the same as an object, there is a design and learning overhead disadvantage.
How would you be able to inherit from the base exception class and derive your own exception class for your module if they were not first type citizens?
I don't see why I shouldn't be allowed to pass and return exceptions as normal method parameters. What if I were writing an Exception Handling library? What if I were writing a unit test assertion that compared exceptions?
Because life is a lot easier that way. Among other things, it means that the exception object can contain information that the program can use to correct the exceptional situation (perhaps with human intervention).
Abend is so 1960s.
I'm not sure the example you give is a strong enough case for not having exceptions as objects. After all you COULD do all kinds of "smelly" or "bad" things while programming. However thats precisely the reason we want good programmers. Just because I can do dsomething like :
def get_total
return nil
end
surely doesnt mean I should not allow nil as an instance of an object!

Which Error Handling Model Is More Robust?

I'm kind of torn between these two error-handling models:
Create a boolean Error and a string ErrorMessage property for your object. Catch all exceptions internally in the object's methods and pass the messages along using conditional logic from the caller, ie:
Dim o As New MyObject
o.SomeMethod()
If Not o.Error Then
'Do stuff'
Else
Dim msg As String = o.ErrorMessage
'do something with message'
End If
Throw exceptions in your object and handle them on the outside with Try Catch logic:
Dim o As New MyObject
Try
o.SomeMethod()
'Do stuff'
Catch ex As Exception
Dim msg As String = ex.ErrorMessage
'do something with message'
End Try
To me, it seems like the same amount of code either way, except that you have property code for the Error and ErrorMessage properties. However, you also can tell when an error occurs without having to check for exceptions. Which pattern should I go with?
I have decided to go with throwing exceptions instead of using error/return codes. I just recently looked really hard into this.
The #1 reason to throw exceptions is there is a possibility you can forget to check the error code. If you don't check it, then you will continue working while the error exists. With exceptions though, if you forget to handle them, then the exception will raise to the top and stop all processing. It is better for this to happen than to continue after unknown errors have occurred.
For more info check out the Exception chapter in Framework Design Guidelines: Conventions, Idioms, and Patterns for Reusable .NET Libraries, Second Edition by Addison-Wesley.
Joel Spolsky actually prefers error/return codes over exceptions but a lot of people disagree with him. Joel's post in favor of return codes can be found here. Check out this blog post and all of the comments with some good discussion regarding this subject.
Prefer #2. For details, see this excerpt on Exception Throwing from the development of Microsoft's excellent Framework Design Guidelines, as Dennis mentioned. Note especially the section on Exceptions and Performance.
Short version:
Do not return error codes.
Do report execution failures by throwing exceptions.
Do not use exceptions for normal flow of control.
I highly recommend reading the book for a full discussion, complete with commentary from a number of the Microsoft luminaries.
Exceptions should be used when something exceptional has happened.
e.g. you are passed a null (nothing) object when you expect one.
Uncle Bob recommends Exceptions over Error codes in his book Clean code.
He says
The problem with these [error codes] approaches is that they clutter the caller. The caller must check for errors immediately after the call. Unfortunately it's easy to forget. For this reason it is better to throw an exception when you encounter an error. The calling code is cleaner. Its logic is not obscured by error handling.
The biggest issue I have with the first one is that it's passive, easily overlooked and not very standardized. How will a programmer know to check that property? Or which properties / methods can possible set an error? Or which property / method access caused the error to be set?
For example. In your first sample code if o.Error is True, it's unclear whether the initialization of the object or the call to SomeMethod caused the flag to be set.
The exception model is an unignorable way of telling your users that an error occurred. It cannot be avoided without explicit code to handle the situation.
They are both accepted forms of error handling, however the preferred choice for .NET languages is to use exceptions.
There are a few problems with using return codes (either numeric or boolean), the two biggest being:
Easily overlooked/ignored by programmers.
Can't be used in all situations. What happens if your constructor fails? It's not possible for you to return a value explicitly from a constructor.
For these reasons alone, you should use exceptions. Exceptions provide a clean, standardized way to indicate and any failure no matter where it arises.
You will also end up with less code overall as you should only catch exceptions when and where you can safely and appropriately handle that exception.
I recommend using both.
Why?
"Use the right tool for the job"
The "problem" with return codes is that people often forget to handle them. However, exceptions don't solve this problem! People still don't handle exceptions (they don't realise a certain exception needs to be handled, they assume somebody up the stack will handle it, or they use a catch() and squash all errors).
While an unhandled return code might mean the code is in an unstable state, an unhandled exception often guarantees that the program will crash. Is this better?
While a return code is easily identifiable when writing code, it is often impossible (or just tediously time-consuming) to determine what exceptions might be thrown by a method you are calling. This typically results in a lot of very poor exception handling.
Exceptions are supposed to be used for "errors". Therein lies the difficulty. If a file is not found when you try to open it, is that an "error", or an "expected situation"? Only the caller knows. Using exceptions everywhere essentially elevates every piece of status information into an error.
Ultimately, error handling is something a programmer has to work at. This problem exists in both return codes and exceptions.
Thus, I use return codes for passing status information (including "warnings"), and exceptions for "serious errors". (and yes, sometimes it's hard to judge which category something falls under)
Example case from .net:
Int32.Parse throws exceptions (even though none of its exceptions are errors - it is up to the caller to verify the results and decide for themselves if the result is valid). And it's simply a pain (and a performance hit) to have to enclose every call to it in a try/catch. And if you forget to use a try/catch, a simple blank text entry field can crash your program.
Thus, Int32.TryParse() was born. This does the same thing, but returns an error code instead of an exception, so that you can simply ignore errors (accepting a default value of 0 for any illegal inputs). In many real life situations this is much cleaner, faster, easier and safer to use than Int32.Parse().
"TryParse" uses a naming convention to make it clear to the caller that errors might occur, that should be correctly handled. Another approach (to force programmers to handle errors better) is to make the return code into an out or ref parameter, so that the caller is explicitly made aware of the need to handle returned errors.

C++\CLI exception specification not allowed

I'm an experienced unmanaged C++ developer, new to C++\CLI.
How come managed C++ doesnt allow exception specification?
Example link
What's the best practice for specifying exceptions my methods throw then?
Presumably because the CLR doesn't use exception specifications; this in turn is presumably because Microsoft looked at Java and decided that they are far more trouble than they are worth.
So the best practice for specifying what exceptions your methods throw is to not bother, ie remove your exception specs. It's worth pointing out that even in the normal C++ (ie native) world most people either eschew exception specifications entirely, or only use the empty specification to indicate that the method does not throw.