How to handle a great number of exceptions in java? - android

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

Related

Handle IOException inside function

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!!

Change language to Firebase exceptions

I'm calling to a Firebase method and in case of Exception I want to return the exception message in Spanish but task.getException().getMessage() is returning it in English instead.
Snippet code:
if (task.isSuccessful()) {
// do something
} else {
Toast.makeText(context, task.getException().getMessage(), Toast.LENGTH_SHORT).show();
}
Do I have to change something in Firebase configuration?
Thanks in advance
You can throw the Exception returned by task.getException inside a try-catch-block. All the exeptions that are thrown are in english. Below, each type of Exception that may be thrown by the method you are using.
I have uses an example from the OnCompleteListener for the createUserWithEmailAndPassword() method. Please see the follwing code:
if(!task.isSuccessful()) {
try {
throw task.getException();
} catch(FirebaseAuthWeakPasswordException e) {
//do somethig
} catch(FirebaseAuthInvalidCredentialsException e) {
//do somethig
} catch(FirebaseAuthUserCollisionException e) {
//do somethig
} catch(Exception e) {
Log.e("TAG", e.getMessage());
}
}
Hope it helps.
getLocalizedMessage() does give you the description of the exception (the name is given by task.getException().getClass().getSimpleName()) but still in English (therefore with no difference from getMessage()).
In order to make use of its "localized" features, you first need to override the method according to your needs.
You can see a complete example of how to do that here, although for the simple purpose mentioned here, I would definitely stick with Alex's solution.

Android MVP: Error Handling from Model class / manually trigger error

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;
}
}

Any alternatives for e.printStackTrace(); in android app development?

guys what are the best alternatives for Error Handling in android.
All in all I dont want my application to shutdown in first attempt.
Say it started, made a http request, error and closed.
I am looking for a warning type error and let it continue further functionality.
Thanks in advance.
when trying to print a stack trace you should always use this:
try {
// DO STUFF
} catch (Exception e) {
Log.e(TAG, Log.getStackTraceString(e);
}
Try Log.e(String, String);
Should work for you
try {
//Code
} catch (Exception e) {
System.out.println(e);
}

How to easily add Exception subclasses into catch?

Let's say I need to add some Exception subclasses into catch, such as these ones
...//
catch (ConnectTimeoutException e) {
e.printStackTrace();
} catch (HttpHostConnectException e) {
e.printStackTrace();
}catch (IOException e) {
e.printStackTrace();
}
The first two are (obviously) subclasses of IOException.
How can I add such subclasses into catch in a better (quicker, easier) way than copy/pasting then?
I am confident that IDEA has such automatic feature, but I am not sure which one it is or how to use it.
Alt+Enter on try, Detail exceptions:

Categories

Resources