I have read the articile , and the great solution provided is working perfectly in Activity environment.
I tested it with
int a = 1/0;
in onCreate. And the custom exception handler did triggered.
Currently my app adopted MVP architecture. There are some codes implemeted in Model or Presenter layer like
try {
data = getStringFromFile(fileLocation);
} catch (Exception e) {
e.printStackTrace();
}
which might throw exception. However, the exceptions that caught within Presenter or Model layer is not triggering the default exception handler.
What should I do in order to makes the throwable exception from Model or Presenter layer triggers the custom UncaughtExceptionHandler I had created?
And also, is there anyway to trigger the custom UncaughtExceptionHandler manually by using my self defined exception.
Wrap the code in your presenter in try catch and then throw the exception from catch block to handle it by the parent class:
public void getData() throws Exception
try {
int a = 1/0;
} catch (Exception e) {
throw e;
}
}
Related
I have a method which copies some files from shared memory to internal app memory using the library FileUtils.
The goal is handling IOException in order not to crash the app: it's acceptable if some files are not copied out of the total number.
In the second snippet below there is the called method where the exception is handled.
I need to know 2 things:
a) is there a way to handle the exception only in the called method
and not also in the calling code?
b) in your opinion the exception handling is correct or do I need to add some other code?
Below is the code:
try {
copyfilesfromshared(context);
} catch (IOException e) {
e.printStackTrace();
}
public void copyfilesfromshared(Context context) throws IOException {
for (int ii = 0; ii < numfiles; ii++) {
try {
FileUtils.copyFileToDirectory(files[ii], dirwrite);
} catch (IOException e) {
e.printStackTrace();
}
}
}
is there a way to handle the exception only in the called method and not also in the calling code?
If you handle the exception in copyfilesfromshared() function you do not need to declare throws IOException
public void copyfilesfromshared(Context context) {
for (int ii = 0; ii < numfiles; ii++) {
try {
FileUtils.copyFileToDirectory(files[ii], dirwrite);
} catch (IOException e) {
e.printStackTrace();
}
}
}
Then you can use it normally, without declarin try {...} catch(...) again:
copyfilesfromshared(context);
in your opinion the exception handling is correct or do I need to add some other code?
This looks fine to me, but better check the signature of FileUtils.copyFileToDirectory if it throws any other exception as well, you maybe want to catch here too.
Beside that, it is totally on your side where you wanna handle the exception, but in general the earlier the better.
Heyy,
For your first question
a) is there a way to handle the exception only in the called method
and not also in the calling code?
There is a choise between throwing the IOException from the called method OR
to implement try/catch inside method.
And thats your problem
You are choosing both options instead of one, So just choose one.
And about 2 question
b) in your opinion the exception handling is correct or do I need to
add some other code?
Exception handeling is best at this moment, So don't think and other thought
And that's all!!
Is it possible to auto-restart app after crash using Crashlytics? Unfortunately there is nothing about that topic in docs. I defined my own exception handler which is restarting app, but when i use it crash logs are not sent.
In your custom exception handler you can call Craslytics.logException(exception);.
public class MyExceptionHandler implements Thread.UncaughtExceptionHandler {
#Override
public void uncaughtException(Thread thread, Throwable exception) {
//you should also log the exception to logcat
Log.e(TAG, "UncaughtException", exception);
try {
//log to crashlytics
Crashlytics.logException(exception);
} catch (Exception e) {
Log.d(TAG, "uncaughtException: Crashlytics not initialized, cannot send logs.");
}
//exit with error code 1 (0 is normal program termination,
//which here is not the case)
System.exit(1);
}
}
One thing worth noting is that Crashlytics.logError(...) logs exceptions as "non-fatal". So I usually wrap them so I can differentiate non-fatal exceptions from actual fatal ones.
So:
Crashlytics.logException(exception);
becomes:
//wrap the original exception to your custom 'fatal' exception type.
FatalException fatalException = new FatalException(originalException);
//log with Crashlytics
Crashlytics.logException(fatalException);
Sample from an open source app here.
How to check for a specific exception, e.g. SocketException with message "Socket closed"? We can compare strings like this:
if (exception.getMessage().equals("Socket closed"))...
but is there some more elegant method, like comparing error codes, or comparison with constant exception value?
Except if SocketException is always "Socket closed", but in docs it states that this class is a superclass for all socket exceptions, so there is more than one.
UPDATE:
I don't want to check for exception class. If I do, I would use specialized catch rather than to check tor a class explicitly:
catch (SocketException ex) { ... }
I want some more elegant method to distinct two exceptions which are instances of the same class, not by comparing strings like this:
try {
int i = 2;
if (i == 1) throw new SocketException("one");
else if (i == 2) throw new SocketException("two");
}
catch (SocketException ex) {
if (ex.getMessage().equals("one")) { ... }
}
In this particular case I throw exceptions to show what is it about, but in reality it can be code not controlled by me.
Also I noticed that exception message in one particular case method threw "Socket closed", in another different method threw "Socket is closed". So it's not so reliable to stick to the message either.
Your question has different approaches, depending on what you are trying to achieve. The simplest method for determining if you have the exception you want is to use instanceof since an Exception is a class as well, i.e.:
if (myException instanceof SocketException) {
...
}
However, you then add the requirement of the contents of the message or the possibility that the Exception thrown is actually a subclass of the Exception of interest to you. In the case of a "subclass" you can check if it is a subclass with:
if (myException instanceof SocketException &&
myException.getClass() != SocketException.class) {
// then I'm an instance of a subclass of SocketException, but not SocketExcpetion itself
}
Or conversely, only evaluate for the parent class:
if (myException instanceof SocketException &&
myException.getClass() == SocketException.class) {
// then I'm an instance of the class SocketException, and not a cubclass of SocketExcpetion!!
}
These serve as the "error codes" you seem to be looking for - the identification of the class, with certainty.
However, if you really are interested in the human-readable error contents, then the solution you have should be your implementation. That seems unlikely, but sometimes that is what is required.
You can use:
exception.getClass().getSimpleName() and compare it to SocketException
Hope this helps.
I have some piece of code. In that there are chances to get many number of exceptions. My doubt is, to handle all those exceptions do i have to write catch blocks for each type of exception. Is it an efficient way or not. Except using throws keyword, If any other solutions are there please suggest me to do that. Any response will be appreciated.
Thanks in advance
It depends on what kind of exceptions you're trying to catch. Everything that can be thrown implements Throwable, so you can catch everything with
} catch (Throwable t) {
including run time errors and all. As Amjad mentions, you can narrow that a little with
} catch (Exception e) {
which just catches Exception and its subtypes.
The problem with both of these is that they catch too much; you can work around that but you risk catching an important problem and then not handling it.
If you have just a few different exceptions, you're probably best off with an exception comb
} catch (Exception1 e) { // do something
} catch (Exception2 e) { // do something else
You have one other option if these are your own exceptions: make a class hierarchy of your own exceptions
class MyExceptions extends Exception { /* ... */ }
class MyExceptionSubtypeA extends MyException { /* ... */ }
class MyExceptionSubtypeASubsub1 extends MyExceptionSubtypeA { /* ... */ }
Now you can pick any subtree of classes, as with
} catch (MyExceptionSubtypeA sa) {
which will catch both MyExceptionSubtypeA and MyExceptionSubtypeASubsub1.
Use the general kind of exception Exception
try{
//your code here
}
catch(Exception e){
//handle exception
}
However this is unrecommended http://source.android.com/source/code-style.html#exceptionsAll
I'm currently working on an XMPP app' on Android and I'm pondering about the best way to throw a different type of Exception than a RemoteException to my activity from my service.
As it seems impossible to throw another thing than a RemoteException using IPC (you can't declare to throw anything in your .aidl), I just see two solutions:
Create a listener for my activity to listen on my custom XMPP exception, which in fact will not be thrown but just sent as a usual object implementing the Parcelable protocol.
Catch my XMPPException and throw a RemoteException (with a content updated with my XMPPException) - But in that case, how could I know on my activity if it's an XMPP or a real RemoteException ? By tagging the name of the exception and parsing it on my activity ? It would be really gore.
Do you have any idea ? Did I miss something from the SDK documentation ?
Thanks.
If #1 means what I think it does, I'd use that -- have the service catch the exception and call a method on an AIDL-defined callback object created and supplied by the activity.
You can see an example of that technique in this client and service project, from one of my books.
It looks like we can throw custom exceptions derived from RemoteException. So you can have XMPPRemoteException, or just a generic MyRemoteException that will hold the original exception. Below is a demo for the second case:
Server:
try {
...
}
catch(XMPPException e) {
throw new MyRemoteException(e);
}
Client:
try {
service.someCall();
}
catch(MyRemoteException e) {
rethrow(e);
}
Helper method:
private void rethrow(MyRemoteException e) throws Exception {
if(e.innerException instanceof XMPPException)
throw (XMPPException)e.innerException;
else
throw e.innerException;
}
Exception:
public class MyRemoteException extends RemoteException {
private static final long serialVersionUID = 1L;
public Exception innerException;
public MyRemoteException() {}
public MyRemoteException(Exception innerException) {
this.innerException = innerException;
}
}
I think it is impossible to achieve "Throw a custom exception from a service to an activity".
See the resource of Parcel:
/**
* Use this function for customized exception handling.
* customized method call this method for all unknown case
* #param code exception code
* #param msg exception message
*/
public final void readException(int code, String msg) {
switch (code) {
case EX_SECURITY:
throw new SecurityException(msg);
case EX_BAD_PARCELABLE:
throw new BadParcelableException(msg);
case EX_ILLEGAL_ARGUMENT:
throw new IllegalArgumentException(msg);
case EX_NULL_POINTER:
throw new NullPointerException(msg);
case EX_ILLEGAL_STATE:
throw new IllegalStateException(msg);
}
throw new RuntimeException("Unknown exception code: " + code
+ " msg " + msg);
}
so we can know that we just can throw these five exceptions above.
for example:
If your service throw a IllegalArgumentException:
#Override
public void addImage(final int align, final byte[] imageData) throws RemoteException {
log("/// addImage ///");
if (imageData == null) {
throw new IllegalArgumentException("The second argument(image data) can not be empty!");
}
...
}
your client will can catch it:
try {
printer.addImage(0, null);
} catch (IllegalArgumentException e) {
e.printStackTrace();
}