(Neko) "alc_cleanup: 1 device not closed" instead of error message - exception

I'm making a game using Haxe and targeting neko. Any uncaught exception leads to alc_cleanup error.
The problem is, this error blocks the output of the exception details.
It's annoying because I use assertions so I can't find out which one threw an exception if one of the tests fail.
Any help here?

The alc_cleanup error simply happens because an OpenAl audio device in use (by your game or an underlying framework) hasn't been closed before terminating the program (due to the uncaught exception).
If you can, you might want to catch and log that exception yourself to prevent it from being corrupted by the alc_cleanup error:
static function main()
{
try {
// do stuff
} catch (e:Dynamic) {
trace('ERROR: $e');
trace(haxe.CallStack.toString(haxe.CallStack.exceptionStack()));
Sys.exit(1);
}
}
You could also:
try to find the proper API in the frameworks you use to destroy the OpenAl context
neko.Lib.rethrow the exception after doing the necessary cleanup yourself

Related

Difference between throwing Exception and throwing a specific Exception such as NullPointerException

I am wondering what is the difference between throwing just Exception and throwing a specific Exception such as NullPointer Exception.
To my current knowledge an Exception should be able to catch any type of exception where as using a specific Exception expects that only that exception type can be thrown.
Example:
void test(String testString) throws Exception;
vs
void test(String testString) throws NullPointerException;
If this is correct than to me it makes sense to just always throw Exception and to never name a specific exception. Am I missing something important here? Does it at the very least effect performance at all? A lot of people are looking between throwing and catching exceptions but nobody asks this very basic question.
I do not see a benefit of throwing any exception except Exception.
To start off, Exception is a base type of every Exception. Just like object is for everything.
By throwing a specific Exception you provide more information to the consumer of what has happened.
Imagine scenario where you get a plain Exception without a message, consumer is lost. When for example framework throws a NullReferenceException, then you are aware of a fact that one of your objects does not have a reference which it was trying to access.
This is how you can chain exceptions and make use of their types:
try
{
throw new NotImplementedException();
}
catch(NullReferenceException ex)
{
// Logic for NullReference exception if needed.
}
catch(NotImplementedException ex)
{
// This will be executed.
}
catch(Exception ex)
{
// Will catch every exception.
}
There are at least two reasons why you would want to throw a specific kind of exception:
If a program fails with an exception, you will have more information with which to determine what went wrong. Compare seeing Exception with FileNotFoundException. The latter clearly gives you more information.
In some cases, the code will want to catch certain kinds of exceptions. For example, when working with serial ports, you might want to catch and handle a TimeoutException differently from a NullReferenceException.
The NullPointerException you mentioned is a very good example from the regular Exception because it is a subclass of RuntimeException. Any throwing of (a subclass of) RuntimeException does not have to be caught or declared.
Any other (=not a subclass of RuntimeException) Exception has to be handled in your code by either a try/catch block or a throws declaration. Otherwise, your code will not even compile! That forces you as a developer to handle errors that might pop up.
As for why using different Exception types is useful, consider the following simple example that uses multiple catch statements:
void doDBStuff(){
try {
performStatement(someStatement);
} catch(SQLException e){
//invalid SQL syntax, something is broken
} catch(AuthenticationException e){
//invalid user credentials for the db, inform the user to change these values
}
In this example, two different exceptions end up in two different catch blocks which lets you handle these errors differently.
It's a best practice to throw specific exceptions, instead of a generic one. This is because the caller might want to treat the exceptions differently, for example in a WebApi you might want to return a Bad Request response (400) for a ArgumentNullException, but you might want to return a different result for other types of exceptions. For example you might actually throw a custom NotFoundException and then the controller would catch it and return a Not Found response (404) instead.
Basically if you throw specific exceptions you are allowing the consumer code to handle the different exception scenarios the way they want.

What is the usefulness of using throw? and in catch?

From what I understand throw causes an exception.
It looks like it can be used to test your catch exception.
What are the benefits/uses for it? Why would you want to purposely cause an exception?
Why use throw in catch? Seems like it catches the exception just to cause an exception again.
try
{
//blah
}
catch
{
throw;
}
throw; rethrows the current exception. It's used for when you want to catch an exception and do some handling of your own, but otherwise still want the exception to propagate more-or-less as if you never caught it.
The difference (in languages that let you just say throw;, like C#) is that when you rethrow an exception, the original stack trace remains mostly intact. (It includes the line where you rethrew the exception rather than the line where the exception occurred in the corresponding try block, but otherwise the whole stack trace is preserved.) If you say throw the_exception_you_caught;, it's usually treated as if you threw a brand new exception from right there -- the existing stack trace gets obliterated and a new one starts from that point.
Exceptions are mechanism for error handling. For instance, you may throw an exception to indicate that a webservice call has timed out, or bad input as been provided to a method. The idea is that calling code knows how to deal with these exceptions and handles them gracefully — perhaps fixing what's wrong in the case of bad input (by prompting the user) or by trying a callout a second time.
A catch block is where you do your handling of the error, and in certain scenarios you may want to do some local cleanup in the method running, but then you still need to report the error to calling methods, so you throw the exception once more (or throw a different, maybe more generic or specific exception) which you then handle in your calling code.
Description
You can do this to, for example, log something and give the exception back to the calling method / assembly.
You can handle the exception and signals the caller that a exception is happend instead of return a boolean that indicates if the method has success.
This is useful for unit tests and more.
Sample
try
{
//blah
}
catch
{
// log exception to textfile of database
throw;
}
This is a common pattern in .Net code. It's used when the caller wants to either log, wrap or react to an exception and then pass it back up to the caller. For example
try {
SomeFunction();
} catch {
CloseMyResource();
throw;
}
The advantage of throw vs throw exceptionVariable is that throw preserves the original stack trace. The next person to catch the exception sees the original stack trace. This is essentially for tracking down errors in deep call stacks.
I think it may be better to think of a throw as your informed reaction to an exception in your code rather than the cause. Semantics I know but it helps.
You throw a different exception in a catch to add information. Your converting what may be a generic OS exception into one meaningful to your application. e.g. Out of memory exception may be caught and a new exception with the out of memory as the inner exception be throw saying something like "Error while computing the answer to life the universe and everything". More useful that just an out of memory exception.
You may use a 'throw' on its own as a rethrow. The catch allows you to do something before rethrowing. If we are talking C# check out 'finally'.
When something really bad happens, that ought not happen, then you can abort and inform the caller by throwing an exception. It means that you do not need to have every method returning result codes and every caller testing fault/success codes. It also nicely abstracts who handles such 'exceptions' or even if you just leave it to the OS.
Quick answer ... it makes your code simpler and gives you better control of aborting and handling exceptions. Think of it as a messaging/abort system.
You would re-throw the same exception if you wanted to do some logging here or some clean up but would like to still have the calling functions further up the call stack to have to handle that same exception.
A more typical use would be:
try {
// ...
} catch (EmailException ex) {
SMS.AlertError("Email is not working", ex);
throw;
}
If you throw ex you will have stripped out information such as the call stack from the exception.
The some function above that would:
try {
// ...
} catch (Exception ex) {
WorkFlowProblems.Add(new OrderNotSentException("Email did not work", ex));
View.ShowError("Could not send order!");
}
Here you make a new exception and set it's "inner exception" to be original cause. This is a good way for multi-part systems to have the right level of information about what went wrong and at what level.
Doing this preserves the stack trace. In your example, it's not useful, however, you could catch the exception, log it and then rethrow so that the exception bubbles up to be handled by code higher up.
The place where throwing exception (in my opinion) is MOST useful is when you want to create an instance of a new object and there's some possibility that the instance needs to fail in creation, in which case the instance can be made to remain null (since constructors don't "return" anything... so for example...
Foo foo = new Foo();//
//at this line foo may or may not be the exact thing you want it to be, depending on whatever conditions made the creation of Foo possible.
So, Foo throws an exception you can do this:
Foo foo = null;
try{
foo = new Foo();
}catch(FooException fe){
//here you can find out if Foo didn't get instantiated as you wanted it to
}
//and here you can test if foo is still null.

Problem with FlexUnit4

I"m a bit confused because FlexUnith 4's behavior. When I use fail() in try-catch body fail method is just ignored.
[Test]
public function extend():void
{
try {
fail("This should fail");
} catch(er:Error) {}
}
I suppose this one should fail as there is no way around it, but it succeeds and turns green. Whatam I doing wrong? When i put fail() before try-catch block it fails as it is suposed to. BTW using Flash builder 4.
The way assertions are signaled to the framework is through exceptions. fail sends the failure signal using an exception too. That, and the fact that Error is the base class for all exceptions means that no exception will ever reach the framework (your try/catch block catches all excpetions), which means that the test didn't fail.

How to deal with exceptions

My technical lead insists on this exception mechanism:
try
{
DoSth();
}
catch (OurException)
{
throw;
}
catch (Exception ex)
{
Util.Log(ex.Message, "1242"); // 1242 is unique to this catch block
throw new OurException(ex);
}
1242 here is an identifier of the catch method which we handle an exception other than OurException. Every catch block in the project must have a unique identifier so we can know where the exception occurred by looking at the logs.
For every method, we have to catch OurException and throw it. If an other type of exception is thrown, we have to log it and mask it by OurException before rethrowing it.
Is this a reasonable approach? If there are any, what are the better alternatives?
Edit: I've been told the stack trace does not produce meaningful results in release mode.
Are you suggesting catching and throwing generic exceptions is OK?
Edit2: Thank you all. I used your answers as part of my argument against this but I've been told you are not experienced enough and do not know how to deal with real life situations. I have to go this way.
You can also look into the Exception Handling Application block.
I have used it in a few projects and it is very useful. Especially if you want to later change how your exception handling works, and what information to capture.
I would think that using the stack trace would be much more intuitive than any identifier.
As far as the custom exception, why not do this?
try
{
DoSth();
}
catch(Exception ex)
{
Util.Log(ex.Message, ex.StackTrace);
if(ex is OurException) throw ex;
else throw new OurException(ex); // use the original exception as the InnerException
}
Also, I'm not sure why you'd want to rethrow an exception after it's been handled - can you explain the reasoning behind that?
#Ali A - A very valid point, so allow me to rephrase - why rethrow the exception instead of finishing the handling of it right here?
EDIT:
Instead of rethrowing, why not do this?
try
{
DoSth();
}
catch(Exception ex)
{
Util.HandleException(ex);
}
Util.HandleException:
public static void HandleException(ex)
{
Util.Log(ex); // Util.Log should log the message and stack trace of the passed exception as well as any InnerExceptions - remember, than can be several nested InnerExceptions.
// Any additional handling logic, such as exiting the application, or showing the user an error message (or redirecting in a web app)
}
That way, you know every exception only gets logged once, and you're not throwing them back into the wild to wreak any additional havoc.
Having the OurException is kinda weird. Usually, you want to have specialized catch blocks and then the last one, the one that catches a generic Exception is where you do your logging:
try
{
DoSomething();
}
catch (DivideByZeroException)
{
// handle it here, maybe rethrow it, whatever
}
// more catch blocks
catch (Exception)
{
// oops, this is unexpected, so lets log it
}
But what your doing will work. I do believe the 1242 should go though. Here's a method to print the method, filename, and line number you could use instead. I haven't tried it myself but it looks good:
[Conditional("DEBUG")]
public static void DebugPrintTrace()
{
StackTrace st = new StackTrace(true);
StackFrame sf = st.GetFrame(1); // this gets the caller's frame, not this one
Console.WriteLine("Trace "
+ sf.GetMethod().Name + " "
+ sf.GetFileName() + ":"
+ sf.GetFileLineNumber() + "\n");
}
I have two types of exceptions: repairable exception and fatal exception. If some object throw repairable exception, this is mean that error occur but object is not damaged and can be used over again. If some object throw fatal exception, this is means that object state is damaged, and any attempt to use object will lead with new error.
Update: all exceptions might be handled as soon as possible, and as close to error source as possible. For example, if object, stored in collection throws the fatal exception, exception handler just remove this object from collection and delete it, not all entire collection of objects.
From what I understand, the purpose of exceptions are to propagate unexpected errors. If you catch it close enough to the method that throws it, you are more in the context of how to handle it.
Your example is to catch an unexpected error, and rethrow that up the chain. This is not handling the exception, but wrapping it into your own.
But your wrapping does not seem to add any more value to the exception, but might even clutter things.
An extreme example:
void a() {
try {
c();
} catch(MyException1 ex) {
throw;
} catch(Exception ex) {
log(ex);
throw new MyException1(ex);
}
}
void b() {
try {
a();
} catch(MyException2 ex) {
throw;
} catch(Exception ex) {
log(ex);
throw new MyException2(ex);
}
}
Notice how that, in the earlier example, the original exception is logged twice. And it is wrapped in two exceptions.
When you log the same exception a few times it becomes harder to trace (since the log file grows rather big).
Of course this might be an extreme example, but I find it hard to believe that your entire application has only one type of exception in use. It does not describe sufficient all the different types of errors that might happen.
I personally prefer to log the exception only at the catch block where I handle it. Anywhere else might just create duplicated logging.
I think that having a hard coded number on the throw line is not a good practice, how do you know whether that number is being used or not?, or, which is the next error number to throw? Maybe you can have, at least, listed on an enum... not sure.
Everything looks right except for that weird number.
The stack trace will contain the information you need.
Seems to me that the stacktrace is a better way to handle this. What happens if you mistakenly reuse a number?
As far as whether this is a good idea or not, in the absence of any more information, I'd tend to say no. If every method invocation is wrapped in a try/catch block it will be very expensive. Generally, exceptions fall in to two camps -- those you can reasonably expect and deal with and those that are really bugs (or at least not successfully anticipated). Using a shotgun approach to catching all exceptions seems to me like it just might do more to hide the latter than help get them resolved. This would be especially true if at the top level you caught all exceptions so that the only record you have is the log message.
I fail to see how this is helpful. You can already know where the exception came from with the stack trace, and you are adding an unnecessary level of complication.
The drawbacks:
That number doesn´t inspire much confidence, stack trace is much better
Why have 2 catch blocks if your custom exception can be handled on the "catch(Exception ex)
"?
I think this is a bad pattern, because you have the information about the whole call stack readily available in the exception, there is no need to pseudo-handle the exception by logging and rethrowing it. Only catch an exception at a place where you really can do something about the problem.
Logging the stacktrace would be a lot better than the hardcoded number. The number tells you nothing about what routine called this one.
Also the number is a pain to manage, and error-prone at that.
edit: it is true that the stacktrace doesn't always produce meaningful results in release mode, but I think the same can be said of this hardcoded number scheme! :-)
With the language you're using, does the compiler provide macros with the current filename and line number? That would be better than trying to roll a unique number yourself. And, if you can't do that automatically, do it manually, or come up with some scheme to guarantee uniqueness that doesn't require some central allocation of numbers!
My application is built in release mode, and i use the Exception Handling Application Block, so i never have any catch ex blocks of code, it is caught by the EHAB, this itself writes to a log file with all the info i need; stack trace etc, time, etc.
the only problem with this is if someone has put
catch ex
{
//do stuff
throw ex;
}
as this will wipe out the stack trace.

When to dodge exceptions and when to handle them

What guidlines do you use when deciding whether to let a method dodge an exception (ie: let the exception propogate up) or handle it once the exception is recieved?
Here is an example of what I am trying to ask
If I have three methods method1,2,3 and 3. Method1 calls Method2 which Calls Method3. and the exception is only thrown in method 3 when should I let the exception propogate upward as follows (excuse my pseudo java ;) )
method1 {
try {
call method2;
} catch (exception e) {
doErrorProcessing;
}
}
method2 throws exception {
call method3;
}
method3 throws exception {
call readFile;
}
And when should I handle the exception once it is raised as follows
method1 {
call method2;
}
method2 {
call method3;
}
method3 {
try {
call readFille
} catch (exception e) {
doErrorProcessing;
}
}
The rule I follow:
If I can fix an exception, or nullify the problem that caused it (sometimes this means just ignoring it altogether), I'll handle it. Otherwise it gets passed up to the next level.
And I always try to fix exceptions as low in the tree as possible (i.e. as soon as possible after they occur) - this localizes exception handling and avoids big honkin' exception handlers in your upper levels.
Like all answers in software, this one for me is "it depends".
Most exceptions should be, in fact, exceptional, so generally I tend to like them to break the app when they occur. If the exception represents some recoverable error condition, then it should be handled at the point in the call stack when you have the information you need to do so safely. This would include situations where the error can be corrected by the user, i.e. catching the exception to report it back to the user so that they can take appropriate actions.
If the lower level routine knows what to do about the exceptional condition, it should probably handle it. If it is an exceptional condition unrelated to the task that function is intended to perform, it would probably make more sense to let it be handled at a higher level.
Only catch exceptions you can handle. Let everything else pass you by.
From a Java point of view, I always try and use unchecked exceptions to avoid adding the throws declarations in the method signatures.
Then where I actually catch the exception will be depending on the situation. I'd always want to handle the exception as high in the chain as possible where the exception is applicable. And if it's a system level exception where you expect the application to fall over, then I might have an exception handling mechanism where it will "catch all".