When you write a class which throws exception, is it a good idea to handle the exception within the class? Or is it better to let the user of the class handle it in the main program?
for example, is it a good idea to write a class with the following?
class Queue{
Object Queue<Object>::getFront( )
{
try
{
if( isEmpty( ) )
throw Underflow( );
} catch(Underflow E)
{
cerr<<"caught underflow\n";
return null;
}
return queuearray[ front ];
}
}
or is it better to just have
Object Queue<Object>::getFront( )
{
if( isEmpty( ) )
throw Underflow( );
return queuearray[ front ];
}
and then let the user implement the exception in the main or wherever the function is
being called?
It depends on where it's best to handle the exception. If the exception is recoverable and doesn't affect the flow of the program then you can quietly handle it and log it. If you think that the caller might be able to better decide what to do, then throw the exception.
Remember that you should only be using exceptions where the circumstances are really exceptional - things outside of the control of the application. The example that you state above isn't really ideal. If you are throwing the exception, why bother catching it on the line below? Just do
class Queue{
Object Queue<Object>::getFront( )
{
try
{
if( isEmpty( ) )
return null;
}
return queuearray[ front ];
}
}
}
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
}
we have different types of exceptions for array expression and intiger expression one by one I need to handle the both exception one by one at a time by using single try block ....please give me answer
Assuming Java code, you may try this:
try{
// do your operation here
} catch( Exception e ){
if( e instanceof ArrayExpressionException ){
// handle it
}
else if( e instanceof IntegerExpressionException ){
// handle it
}
else {
throw e;
}
}
The type of the exception declared in the catch block doesn't have to be java.lang.Exception. It has to be a type that is a common supertype of both ArrayExpressionException and IntegerExpressionException, though. It could be ExpressionException, for instance, if it exists.
I have a service method which does some operation inside a transaction.
public User method1() {
// some code...
Vehicle.withTransaction { status ->
// some collection loop
// some other delete
vehicle.delete(failOnError:true)
}
if (checkSomething outside transaction) {
return throw some user defined exception
}
return user
}
If there is a runtime exception we dont have to catch that exception and the transaction will be rolled back automatically. But how to determine that transaction rolled back due to some exception and I want to throw some user friendly error message. delete() call also wont return anything.
If I add try/catch block inside the transaction by catching the Exception (super class) it is not getting into that exception block. But i was expecting it to go into that block and throw user friendly exception.
EDIT 1: Is it a good idea to add try/catch arround withTransaction
Any idea how to solver this?? Thanks in advance.
If I understand you question correctly, you want to know how to catch an exception, determine what the exception is, and return a message to the user. There are a few ways to do this. I will show you how I do it.
Before I get to the code there are a few things I might suggest. First, you don't need to explicitly declare the transaction in a service (I'm using v2.2.5). Services are transactional by default (not a big deal).
Second, the transaction will automatically roll back if any exception occurs while executing the service method.
Third, I would recommend removing failOnError:true from save() (I don't think it works on delete()... I may be wrong?). I find it is easier to run validate() or save() in the service then return the model instance to the controller where the objects errors can be used in a flash message.
The following is a sample of how I like to handle exceptions and saves using a service method and try/catch in the controller:
class FooService {
def saveFoo(Foo fooInstance) {
return fooInstance.save()
}
def anotherSaveFoo(Foo fooInstance) {
if(fooInstance.validate()){
fooInstance.save()
}else{
do something else or
throw new CustomException()
}
return fooInstance
}
}
class FooController {
def save = {
def newFoo = new Foo(params)
try{
returnedFoo = fooService.saveFoo(newFoo)
}catch(CustomException | Exception e){
flash.warning = [message(code: 'foo.validation.error.message',
args: [org.apache.commons.lang.exception.ExceptionUtils.getRootCauseMessage(e)],
default: "The foo changes did not pass validation.<br/>{0}")]
redirect('to where ever you need to go')
return
}
if(returnedFoo.hasErrors()){
def fooErrors = returnedFoo.errors.getAllErrors()
flash.warning = [message(code: 'foo.validation.error.message',
args: [fooErrors],
default: "The foo changes did not pass validation.<br/>${fooErrors}")]
redirect('to where ever you need to go')
return
}else {
flash.success = [message(code: 'foo.saved.successfully.message',
default: "The foo was saved successfully")]
redirect('to where ever you need to go')
}
}
}
Hope this helps, or gets some other input from more experienced Grails developers.
Here are a few other ways I've found to get exception info to pass along to your user:
request.exception.cause
request.exception.cause.message
response.status
A few links to other relevant questions that may help:
Exception handling in Grails controllers
Exception handling in Grails controllers with ExceptionMapper in Grails 2.2.4 best practice
https://commons.apache.org/proper/commons-lang/javadocs/api-2.6/org/apache/commons/lang/exception/ExceptionUtils.html
I'm developing a J2ME Application and I want to make a good practice for Exception Handling, I'm throwing some exceptions like
ConnectionNotFoundException, IOException, XmlPullParserException, OutOfMemory, Exception
I don't want to catch all these exception in each method that I make
so I think that I can make a new class
and this class will handle all others
I have made this class
public class ExceptionHandler extends Exception {
private Exception thrownException;
public ExceptionHandler(Exception thrownExc) {
this.thrownException = thrownExc;
if (thrownException.getClass().isInstance(ConnectionNotFoundException.class)) {
// DO SOMETHING
} else if (thrownException.getClass().isInstance(IOException.class)) {
// DO SOMETHING
} else if (thrownException.getClass().isInstance(XmlPullParserException.class)) {
// DO SOMETHING
} else if (thrownException.getClass().isInstance(NullPointerException.class)) {
// DO SOMETHING
} else if (thrownException.getClass().isInstance(OutOfMemoryError.class)) {
// DO SOMETHING
} else if (thrownException.getClass().isInstance(Exception.class)) {
// DO SOMETHING
}
}
}
but I don't know if that is a good way or not and also I have error when I replace the thrown exceptions with mine
so what can I do please ?
You are on the right track, that is the best way to handle errors. You can also pass a second argument called message in your custom exception class and then display message here itself. Something like this:
if (thrownException.getClass().isInstance(ConnectionNotFoundException.class)) {
Dialog.alert(msg);
}
Also from the calling class, you just callnew ExceptionHandler(exception, Constants.msg)
The Constants.java class will hold all the error messages.
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.