Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Failure failing in CATCH

I'm probably overlooking something simple, but I do not expect the below code to fail. It is behaving as if I wrote die instead of fail in the catch block.

The Failure does not get properly handled and the code dies.

sub foo() 
{
  try {
    say 1 / 0;
    CATCH { default { fail "FAIL" } }
  } 

  return True;
}

with foo() { 
    say "done";
}
else
{
  say "handled {.exception.message}"
}

Output:

FAIL
  in block  at d:\tmp\x.pl line 5
  in any  at d:\tmp\x.pl line 5
  in sub foo at d:\tmp\x.pl line 4
  in block <unit> at d:\tmp\x.pl line 11
like image 224
Holli Avatar asked Sep 28 '19 19:09

Holli


People also ask

How do you handle errors in catch block?

You can put a try catch inside the catch block, or you can simply throw the exception again. Its better to have finally block with your try catch so that even if an exception occurs in the catch block, finally block code gets executed.

Can we use error in catch block?

Yes we can catch Throwable but as best practice, it is not advised to catch Throwable . Catching Throwable includes Errors too, we should not catch errors, it helps to identify JVM issues.

Is try catch better than if?

In general, try-catch blocks are great because they will break (move to the catch statement) whenever the exception occurs. If-else blocks rely on you predicting when the error will happen. Edit: Also, catch blocks won't stop your code from halting when an error is hit.

Why you should not use try catch?

Without a try catch, you run the risk of encountering unhandled exceptions. Try catch statements aren't free in that they come with performance overhead. Like any language feature, try catches can be overused.


Video Answer


1 Answers

To bring home to later readers the full force of what Yoda said in their comment, the simplest solution is to unlearn the notion that you have to try in order to CATCH. You don't:

sub foo() 
{
  say 1 / 0;
  CATCH { default { fail "FAIL" } }
  return True;
}

with foo() { 
    say "done";
}
else
{
  say "handled {.exception.message}"
}

correctly displays:

handled FAIL
like image 179
raiph Avatar answered Sep 24 '22 08:09

raiph