I'm looking at NLua for scripting of an existing C# application, where C# functions called from lua may throw exceptions.
So far, I found this:
If the lua code does not handle an exception in a called C# function, NLua wraps and re-throws it so it can be handled at C# level.
If lua code does "catch" an exception via xpcall, I have found no way to access the exception's details (e.g -.Message)
The former allows me to get a debug.traceback(), a lua-level stackdump, but I don't get details of the exception.
The latter provides the exception, but no way to get a Lua stackdump (I get lua file and line in .Source, but that isn't enough).
The question is:
Can I get details of a C# exception in a NLua "xpcall" error handler (? At least the .Message field, even better the actual exception type.
Alternatively, can I handle a C# exception in NLua (with the intention of creating a lua stackdump) and re-throw it?
Or can I get a lua stackdump somehow from the "lua state" when e.g.luaState.DoFile("myScript.lua") causes an exception?
Any help would be appreciated. NLua seems near-perfect for what I have in mind, if I could only sort out the exception handling.
You need to use pcall from your script. The NLua will wrap the exception and return on second value returned by pcall.
error, exception = pcall (someFunction)
if (not error) then
print(exception.Message)
end
Example on GitHub.
Related
I am writing a license module (DLL) for multiple applications. This DLL will be used in applications by adding reference. One of the requirement (pass case) for this DLL is that, if license validation fails, calling application should terminate/crash. It should not gracefully shutdown; it must crash. I do not want to show message, write log etc.
DLL and applications (using this DLL) are written in DotNet 4.
Quick solution I can think of is to throw exception instead of returning value from method. But, the exception could be caught by application and purpose will not be fully served.
Workaround for this is to declare custom exception as internal in my DLL. But, this also could be bypassed by catching Exception class.
One dirty alternative I can think of is to write a code (endless recursion or something) that will throw StackOverflowException. But I am looking for something better.
Is there any way to throw custom non-catchable exception?
References:
Ref1 and Ref2 discuss about in built DotNet non-catchable exception. My question is about custom non-catchable exceptions.
Environment.FailFast is the way to go, nothing can then prevent your application from shutting down.
Keep in mind that C# libraries can be easily changed and recompiled, so you might also want to look into using obfuscators as well.
I am trying to integrate a Lua Scripting interface into my C# project by using LuaInterface.
It works as expected if I execute syntactically correct code, but as soon as a syntax error (or any other error as it seems) is introduced to the script an SEHException gets thrown without any information regarding the error.
A simple example to trigger the behavior: new LuaInterface.Lua().DoString("die");
That of course completely nullifies Lua's error handling mechanisms and is a show-stopper for me.
Apparently this is a known bug which is open since 2011.
Are there any workarounds, a version of LuaInterface without this bug or is there an alternative lua wrapper which correctly handles errors?
Lua errors (syntax or runtime errors) encountered by DoString should result in a LuaException being thrown. Its message will contain the error string generated by Lua. For instance, given your example:
try
{
new LuaInterface.Lua().DoString("die");
}
catch (LuaException ex)
{
Console.WriteLine(ex.Message);
}
You should get the following error:
[string "chunk"]:1: '=' expected near '<eof>'
You don't show any context for your one liner. Is it wrapped in a try-catch block?
If so, perhaps it's a bug?
I see there is a problem with the error handling in VBScript, So I would like to fix this using c# code (COM). Here, I need to access Err object of VBScript in c#.net code. I did add the reference namespace VBScript_Global to the project, but VBScript_Global.ErrObj is an abstract class, so could not access it. Is there a way that c# code can watch the Err.Number.
Let me put it more clear,
In VB6, we have On Error GoTo in which if there is a runtime error it automatically drops into error handling code and we can report the error there and do appropriate action.
The same is true with .net and Java (it may be try/catch there).
Where as in VBScript, we have On Error Resume Next (it does not support GoTo ).
On Error Resume Next just moves the controller to the next statement and continue with the execution. Where, we need to explicitly check whether Err.number <> 0 after each statement in the code, which is not feasible to implement.
So I want a generic approach in VBScript, if there is a runtime error, then I should be able to report it somehow.
I thought of writing a dll in c#.net which always checks for the Err.Number of VBScript and report when there is an error occurred. Is this possible? Or my approach is wrong?
Any other alternative suggestions/ideas to handle this situation is appreciated. Thanks.
If the dll cannot do what am looking for, is there a way I can always check whether Err.number of VBScript is NOT 0 out side the VBScript?
VBScript executes in a separate environment. You cannot access an intrinsic VBScript object outside of VBScript, or more appropriately, Windows Script Host.
In our app, we use components developed by other teams. The question was how can I define a nicely way of exception handling than this
try
{
someComponent.DoStuff();
}
catch (Exception ex)
{
textLabel= ex.Message;
}
The component has no custom exception type, maybe a nicely way to do it would be to define a component specific Exception type and wrap this somehow?
I know the question is very basic, but I am interested more in the let's say how it is good to do it. If you call another component with no custom defined exception types, how do you handle any potential exceptions in an elegant way?
Ideally you would have the component development team do this for you - how else do they expect their clients to recognize and handle errors from their component? Scoping the exceptions that a component can raise is a fundamental part of good C# design.
If that's not an option, then implementing your own wrapper on top of the component to taxonomize its failure cases sounds like a good second best, and very noble of you into the bargain.
If the third-party library is poorly documented (they don't specify the exceptions that can be thrown by each method), there are tools available that can Reflect into the code and determine the possible Exceptions that may be thrown. This can get a bit daunting (there are a surprising number of exceptions that can be thrown for any given call), but it's better in principle than catching the general Exception type. Here is one commercial product that performs this type of analysis.
When you catch an error you are able to repackage it and then throw another error, at the most basic level you may just be adding more data - but, from what you've suggested, you could also replace the generic error with a custom error that, whilst it won't overcome the limitations of the response you've got from the component, would give the code further up the call stack the opportunity to respond more appropriately.
So in terms of just adding information in the most basic manner - by throwing a new exception with some additional text whilst still passing the original exception:
catch (Exception ex)
{
throw new Exception("This is more about where the exception occurred", ex);
}
Now, if you want to define your own custom component exception you change the new Exception to new ComponentSpecificException adding data as necessary to the constructor but never forgetting to set the inner exception. Exceptions also have a data collection of key, value pairs into which you can insert more information (by creating the exception, adding the data and then doing the throw).
That's all fairly generic - working forward from there, where you can't necessarily anticipate all the exceptions you have to handle you don't try - you set up logging so that you know when you've got a generic exception i.e. one that hits the final catch - and then over time add exception specific catches above the generic to provide more appropriate responses or, at the very least, package up the error into less general custom exceptions.
Not sure I've explained that very well - but the notion is that as its difficult to anticipate every possible error you want to have a strategy to develop your application in a systematic fashion as you discover new exceptions.
Assuming you want to catch every type of exception, this solution looks fine to me.
Either from your knowledge of using the component, or by using something like Reflector to analyze the compiled component, what possible exceptions can this component throw? Would providing exception handlers for these allow you to provide better feedback to you users?
The only reasonable (much less "elegant") way to handle exceptions is to log them if you can't recover from them.
Then notify the user there was a problem and offer them the chance to try again (if it's an interactive program).
If your application is exclusively for .NET developers, go ahead and show them the exception message (though Exception.ToString is better, since it includes a stack trace). Otherwise, don't display exception messages in your user interface - that's a security hole and will only confuse your users.
I am writing an app and I want to load a file based on a path provided by the user. I check the extension of the file and when the extension does not match anything I recognize I want to throw an exception.
I could throw an IOException. But, I figured there could be a more detailed exception derived from that. So I looked at MSDN and found FileLoadException. The name suggests that my error would fit in this category, but.... when I look on MSDN it says: "Represents the error that occurs when a Assembly file is found but cannot be loaded." and "The exception that is thrown when a managed assembly is found but cannot be loaded." That is absolutely not what is the case with my error.
So what is the question then? Well, I wonder if the documentation actually means that the exception is meant to be thrown for this purpose only or that they just mean that they throw that exception in that specific case, but do not really specify when others should throw it.
On the IOException page on MSDN it does advice to use FileLoadException where appropriate:
IOException is the base class for exceptions thrown while accessing information using streams, files and directories.
The Base Class Library includes the following types, each of which is a derived class of IOException:
DirectoryNotFoundException
EndOfStreamException
FileNotFoundException
FileLoadException
PathTooLongException
Where appropriate, use these types instead of IOException.
Summarized: In case of an unknown file extension, should I throw an IOException or a FileLoadException (I do not want to define my own exception).
Thanks in advance.
You should throw IOException, and never throw FileLoadException which is very specific and "technical" (whereas your exception should be "application oriented"). Try to analyze FileLoadException type with Reflector (in mscorlib), you'll see that it's only used for the purpose defined in the msdn. Then imagine one day your code used in a "plugin context", how will react the host program catching a FileLoadException meaning an assembly failed to load properly ...
I wouldn't throw an exception that is documented to be of a very specific use-case and might confuse others.
If you can't define a new exception, stick with IOException.
FileLoadException wouldn't seem to be a good fit, because it's specifically for assemblies.
IOException is suitable, but it feels very generic and wont let callers handle it gracefully, distinguishing it from more general errors.
If you really have to throw an exception here, consider NotSupportedException, which identifies an attempt to perform an operation which your object does not support, in this case loading a file format you don't recognise.
Good practice is to define your own exceptions: derive one from whether Exception or any other more specific Exception subclass.
This will save your time during testing as well as provide you more information with future feedback: you can differ between some exceptions that are not handled in you code and those your own business logic throws based on your specific rules.
Speaking of this case, I advise you create FileExtensionException derived from IOException. This will pretty much ease you code: you won't have to check error message providing separate catch block for new exception type.
It seems a case of just validating the user data.
Why would you want to throw an exception and just not inform the user that he provided an extension that is not recognized by your application?
If you're using the OpenFileDialog you can even use the OpenFileDialog.Filter in order to allow the user to only select a file with an extension supported by your application.