I have an if condition which checks for value and the it throws new NumberFormatException
Is there any other way to code this
if (foo)
{
throw new NumberFormatException
}
// ..
catch (NumberFormatException exc)
{
// some msg...
}
If you are doing something such as this:
try
{
// some stuff
if (foo)
{
throw new NumberFormatException();
}
}
catch (NumberFormatException exc)
{
do something;
}
Then sure, you could avoid the exception completely and do the 'do something' part inside the conditional block.
If your aim is to avoid to throw a new exception:
if(foo)
{
//some msg...
} else
{
//do something else
}
Don't throw exceptions if you can handle them in another, more elegant manner. Exceptions are expensive and should only be used for cases where there is something going on beyond your control (e.g. a database server is not responding).
If you are trying to ensure that a value is set, and formatted correctly, you should try to handle failure of these conditions in a more graceful manner. For example...
if(myObject.value != null && Checkformat(myObject.Value)
{
// good to go
}
else
{
// not a good place to be. Prompt the user rather than raise an exception?
}
In Java, you can try parsing a string with regular expressions before trying to convert it to a number.
If you're trying to catch your own exception (why???) you could do this:
try { if (foo) throw new NumberFormatException(); }
catch(NumberFormatexception) {/* ... */}
if you are trying to replace the throwing of an exception with some other error handling mechanism your only option is to return or set an error code - the problem is that you then have to go and ensure it is checked elsewhere.
the exception is best.
If you know the flow that will cause you to throw a NumberFormatException, code to handle that case. You shouldn't use Exception hierarchies as a program flow mechanism.
Related
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
}
Depending on database result, some properties of my object may be populated or not.
Lets say I have a task object and if there is a message for it, so it has the $message property populated:
if($task->message === null)
throw new ErrorException('what the ...');
The problem is, whenever I want to check if this property is populated (accessing it), it throws an Getting unknown property exception and the execution terminates.
I think you can try with isset
if (isset($task->message )) {
// your code for is setted
} else {
// your code for not setted
}
Try-catch block also works:
use yii\base\Exception;
[...]
try {
echo $task->message;
} catch (Exception $e) {
// stuff
}
I'm looking to check what type of exception is retruned in the following code snippet.
I'm not sure exactly how to do it though, or if it's even possible.
try {
//SOME LOGIC
} catch (exception ex) {
System.debug(//EXCEPTION TYPE);
}
Would anyone have any suggestions or advice??
try {
//SOME LOGIC
} catch (Exception ex) {
System.err.println(ex.getClass().getName());
}
Few things:
You have posted exception. I assume you meant Exception.
System.debug does not exist.
I have answered your specific question but obviously this is not standard exception handling code. You will instead output the stacktrace, log the exception or rethrow a different one.
Firstly, within your catch block(s), specify the exception. Semantically, types including Exception are not in camel case.
Secondly, you can obtain the exception type through Exception.getClass().getName():
catch (Exception exception) {
System.out.println(exception.getClass().getName());
// exception.printStackTrace();
// throw exception;
}
Specified by:http://docs.oracle.com/javase/7/docs/api/java/lang/Exception.html
After some searching around I found an answer,
try {
//SOME LOGIC
} catch (Exception ex) {
System.debug(ex.getTypeName());
}
The getTypeName() method does the trick nicely.
I apologise for not specifying I was working in Apex in my question.
I am trying my first features with Behat and I am facing the problem I don't know how to implement expected exceptions.
I found the issue https://github.com/Behat/Behat/issues/140 and robocoder is talking about one possible way, which is used by Behat, too. But it seems that they aren't really handling exceptions.
My point is to achieve forced exception handling. I don't want any construct catching all exceptions and forget them.
One possible way would be:
When <player> transfers <transfer> from his account it should fail with <error>
Implementation
try {
...
} catch (\Exception $ex) {
assertEquals($error, $ex->getMessage());
}
I don't like the scenario description. I want to use the then keyword, e.g.
When <player> transfers <transfer> from his account
Then it should fail with error <error>
This description has the disadvantage I need two methods:
method1($arg1, $arg2) {
// Test the transfer
}
method2($arg1, $arg2) {
// Check if the exception is the right one
}
To be able to check in method2 the exception needs to be stored.
The only possible way I see is to use a try/catch and store it to a variable.
Someone else would catch it and do nothing with it. Nobody will notice, when running the tests.
How can I prevent that exceptions are discarded?
Has anybody else a similar scenario implemented?
Thanks for any hints.
EDIT:
Behat context:
playerTransfer($player, $amount) {
$player->transfer($amount);
}
Method from entity class:
transfer($amount) {
if ($this->getWealth() < $amount) {
throw NotEnoughMoney();
}
...
}
Always try to catch method outcome to context class field, for example:
//inside Behat context class method
try {
$this->outcome = $func();
}
catch(\Exception $ex) {
$this->outcome = $ex;
}
Now when expecting exception at next step just check if $this->outcome is instanceof desired exception with message/code.
I think the problem is in your implementation. Do you check if transfer is successful in "When transfers from his account" ? Do you need to check it ?
Failure test:
When <player> transfers <transfer> from his account
Then I should see error <error>
Successful step:
When <player> transfers <transfer> from his account
Then I should see "transfer successful"
Here's how I successfully did it in a project of mine where I had to repeat a few steps till the condition held true:
/**
* #Given /^I execute some conditions$/
*/
public function executeConditions()
{
$flag = 1;
do {
try {
<steps to be executed till the condition holds true>
$flag=1;
} catch (\Exception $ex) {
$flag = 0;
}
}while ($flag>0);
}
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