At compile (macro) time, calling
Context.parse("a bad expression", somePos)
produces an error that cannot be caught in a try-catch block (Edit: this is wrong, see below). Is there a way to catch this error? Context.parseInlineString() doesn't seem to work either.
Others functions such as Context.typeExpr() have a similar problem.
Edit:
The type of catch was wrong. I did:
try {...}
catch (err:String) {...}
What you have to do:
try {...}
catch (err:Dynamic) {...}
Careful reading of the documentation explains this. This is different than Java for which there is one type of exception per error. In Haxe, most errors are strings, but there are some others like the one here.
The following works for me:
import haxe.macro.*;
class Test {
macro static function test() {
try {
Context.parse("a bad expression", Context.currentPos());
} catch(e:Dynamic) {
trace(e); //Test.hx:8: Missing ;
}
return macro {};
}
static function main() {
test();
}
}
Related
I have following code
IAsyncOperation<bool> trythiswork()
{
bool contentFound{ false };
try
{
auto result = co_await someAsyncFunc();
winrt::check_bool(result)
if (result)
{
contentFound = true;
}
}
catch (...)
{
LOG_CAUGHT_EXCEPTION();
}
co_return contentFound;
}
When the result is false, it fails and throws but catch goes to fail fast and program terminates. How does log function terminate the program? Isn't it supposed to only log the exception? I assumed that I am handling this exception so program won't crash but it is crashing.
So how to throw and catch so that program does not terminate? I do want to throw. And also catch and preferably log the exception as well.
Thanks
The issue can be reproduced using the following code:
IAsyncOperation<bool> someAsyncFunc() { co_return false; }
IAsyncOperation<bool> trythiswork()
{
auto contentFound { false };
try
{
auto result = co_await someAsyncFunc();
winrt::check_bool(result);
// throw std::bad_alloc {};
contentFound = true;
}
catch (...)
{
LOG_CAUGHT_EXCEPTION();
}
co_return contentFound;
}
int main()
{
init_apartment();
auto result = trythiswork().get();
}
As it turns out, everything works as advertised, even if not as intended. When running the code with a debugger attached you will see the following debug output:
The exception %s (0x [trythiswork]
Not very helpful, but it shows that logging itself works. This is followed up by something like
FailFast(1) tid(b230) 8007023E {Application Error}
causing the process to terminate. The WIL only recognizes exceptions of type std::exception, wil::ResultException, and Platform::Exception^. When it handles an unrecognized exception type it will terminate the process by default. This can be verified by commenting out the call to check_bool and instead throwing a standard exception (such as std::bad_alloc). This produces a program that will log exception details, but continue to execute.
The behavior can be customized by registering a callback for custom exception types, giving clients control over translating between custom exception types and HRESULT values. This is useful in cases where WIL needs to interoperate with external library code that uses its own exception types.
For C++/WinRT exception types (based on hresult_error) the WIL already provides error handling helpers that can be enabled (see Integrating with C++/WinRT). To opt into this all you need to do is to #include <wil/cppwinrt.h> before any C++/WinRT headers. When using precompiled headers that's where the #include directive should go.
With that change, the program now works as desired: It logs exception information for exceptions that originate from C++/WinRT, and continues to execute after the exception has been handled.
In Python, I would do this:
try:
some_func()
except Exception:
handle_error()
else:
print("some_func was successful")
do_something_else() # exceptions not handled here, deliberately
finally:
print("this will be printed in any case")
I find this very elegant to read; the else block will only be reached if no exception was thrown.
How does one do this in Kotlin? Am I supposed to declare a local variable and check that below the block?
try {
some_func()
// do_something_else() cannot be put here, because I don't want exceptions
// to be handled the same as for the statement above.
} catch (e: Exception) {
handle_error()
} finally {
// reached in any case
}
// how to handle 'else' elegantly?
I found Kotlin docs | Migrating from Python | Exceptions, but this does not cover the else block functionality as found in Python.
Another way to use runCatching is to use the Result's extension functions
runCatching {
someFunc()
}.onFailure { error ->
handleError(error)
}.onSuccess { someFuncReturnValue ->
handleSuccess(someFuncReturnValue)
}.getOrDefault(defaultValue)
.also { finalValue ->
doFinalStuff(finalValue)
}
Take a look at the docs for Result: https://kotlinlang.org/api/latest/jvm/stdlib/kotlin/-result/index.html
If you do not care about the default value, for example, you want just to hide the loading you could use this:
runCatching {
show_loading(true) //show loading indicator
some_func() //this could throw an exception
}.onFailure {
handle_error(it.message)
}.getOrNull().run {
show_loading(false) //hide loading indicator regardless error or success
}
I use Visual Studio Native Unit Test Framework for C++. When an assertion fails, next statements aren't executed and local objects destructors are called, so it seems like an exception is thrown, but I can't catch any C++ exception by catch (...) clause. After some experiments, I noticed that __int2c() call (that triggers the 2c interrupt, due to documentation), for example, has the same effect. By this day I was aware only about exceptions that have such behavior. Could you give me some hint about what can be the reason in this case?
UPDATE:
Here is a code sample
void func()
{
struct Foo
{
~Foo()
{
// this code is executed
}
};
Foo foo;
try
{
Assert::IsTrue(false);
}
catch (...)
{
// this code is not executed
}
// this code is not executed
}
I am running into an extremely strange behavior in Groovy. When I throw an exception from a closure in a Script, the end exception that was thrown was different.
Here are the code and the details:
public class TestDelegate {
def method(Closure closure) {
closure.setResolveStrategy(Closure.DELEGATE_FIRST);
closure.delegate = this;
closure.call();
}
public static void main(String[] args) {
// Make Script from File
File dslFile = new File("src/Script.dsl");
GroovyShell shell = new GroovyShell();
Script dslScript = shell.parse(dslFile);
TestDelegate myDelegate = new TestDelegate();
dslScript.metaClass.methodMissing = {
// will run method(closure)
String name, arguments ->
myDelegate.invokeMethod(name, arguments);
}
dslScript.metaClass.propertyMissing = {
String name ->
println "Will throw error now!"
throw new MyOwnException("errrrror");
}
dslScript.run();
}
}
class MyOwnException extends Exception {
public MyOwnException(String message) {
super(message);
}
}
Script.dsl:
method {
println a;
}
So the plan is that when I run the main() method in TestDelegate, it will run the DSL script, which calls for the method method(). Not finding it in the script, it will invoke methodMissing, which then invokes method() from myDelegate, which in turns invoke the closure, setting the delegate to the testDelegate. So far, so good. Then the closure is supposed to try printing out "a", which is not defined and will thus set off propertyMissing, which will will throw MyOwnException.
When I run the code, however, I get the following output:
Will throw error now!
Exception in thread "main" groovy.lang.MissingPropertyException: No such property: a for class: TestDelegate
Now, it must have reached that catch block, since it printed "Will throw error now!" It must have thrown MyOwnException too! But somewhere along the lines, MyOwnException was converted to MissingPropertyException, and I have no idea why. Does anyone have any idea?
P.S. if I remove closure.setResolveStrategy(Closure.DELEGATE_FIRST) from TestDelegate#method(), the code acts as expected and throws MyOwnException. But I really need the setResolveStrategy(Closure.DELEGATE_FIRST) for my DSL project. And I would prefer to know the root cause of this rather than just removing a line or two and see that it works without understanding why.
I think this is what essentially happens: With a delegate-first resolve strategy, the Groovy runtime first tries to access property a on myDelegate, which results in a MissingPropertyException because no such property exists. Then it tries propertyMissing, which causes a MyOwnException to be thrown. Eventually the runtime gives up and rethrows the first exception encountered (a design decision), which happens to be the MissingPropertyException.
With an owner-first resolve strategy, propertyMissing is consulted first, and hence MyOwnException is eventually rethrown.
Looking at the stack trace and source code underneath should provide more evidence.
I'm trying to leverage the using block more and more these days when I have an object that implements IDisposable but one thing I have not figured out is how to catch an exception as I would in a normal try/catch/finally ... any code samples to point me in the right direction?
Edit: The question was modified after reading through the replies. It was "How to Throw an exception in a using block with .NET 2.0?" but I was actually looking for a way to catch these exceptions inside a using block.
I'm looking for more detail on rolling my own catching block inside a using block.
Edit: What I wanted to avoid is having to use a try/catch/finally inside my using block like #Blair showed. But maybe this is a non issue...
Edit: #Blair, this is exactly what I was looking for, thanks for the detailed reply!
I don't really understand the question - you throw an exception as you normally would.
If MyThing implements IDisposable, then:
using ( MyThing thing = new MyThing() )
{
...
throw new ApplicationException("oops");
}
And thing.Dispose will be called as you leave the block, as the exception's thrown. If you want to combine a try/catch/finally and a using, you can either nest them:
try
{
...
using ( MyThing thing = new MyThing() )
{
...
}
...
}
catch ( Exception e )
{
....
}
finally
{
....
}
(Or put the try/catch/finally in the using):
using ( MyThing thing = new MyThing() )
{
...
try
{
...
}
catch ( Exception e )
{
....
}
finally
{
....
}
...
} // thing.Dispose is called now
Or you can unroll the using and explicitly call Dispose in the finally block as #Quarrelsome demonstrated, adding any extra exception-handling or -recovery code that you need in the finally (or in the catch).
EDIT: In response to #Toran Billups, if you need to process exceptions aside from ensuring that your Dispose method is called, you'll either have to use a using and try/catch/finally or unroll the using - I don't thinks there's any other way to accomplish what you want.
Yeah there is nothing different about throwing exceptions in using blocks.
Remember that the using block basically translates to:
IDisposable disposable = null;
try
{
disposable = new WhateverYouWantedToMake();
}
finally
{
disposable.Dispose()
}
So you will have to roll your own catching if you want to catch anything but catching/throwing is a completely separate concern from the using. The finally is almost guaranteed to execute (save an uncatchable exception (e.g. stackoverflow or outofmemory) or someone pulling the power out of the PC).
You need to have a try statement to catch an exception
Either you can use an try statement within the using block or you can use a using block in a try block
But you need to use a try block to catch any exceptions occuring