Handle IOException inside function - android

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

Related

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

Android: How to check for a specific exception?

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.

Log.d() stops working after calling Integer.parseInt(INVALID_INT)

private void someFunction(String html) {
Document doc = Jsoup.parse(html);
Element vol = doc.select(CSS_PATH).first();
Log.d("Vol", vol.text());
Log.d(TAG, "This gets printed");
Float.parseFloat(vol.text());
Log.d(TAG, "BUT THIS ONE NOT");
}
These two objects are elements of the Jsoup library.
Document doc = Jsoup.parse(html);
Element vol = doc.select(PATH.PEAK_DOWN_VOL).first();
vol.text() returns a String containing a float value.
Log.d("Vol", vol.text()); // logs something similar to 'Vol: 12.4'
But after calling Float.parseFloat(peakDownVol.text());, Log.d in this class will stop entirely. But Log.d's in the Activity class seems to work just fine.
If I change Float.parseFloat(vol.text()); to Integer.parseInt(vol.text());, it logs the subsequent statements without any problem.
I have lot of number parsing to do. So I'd like to know why is this happening exactly?
If you want the rest of the method to run regardless, you should catch the potential exception locally, so that the program can continue executing the rest of the method and not bubble back up the call stack until it finds an exception handler or crashes for the lack of one:
Log.d(TAG, "This gets printed");
try {
Float.parseFloat(vol.text());
} catch (NumberFormatException e) {
e.printStackTrace(); //leave evidence in the log
}
Log.d(TAG, "So does this");

How to handle a great number of exceptions in java?

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

Should I remove e.printStackTrace() from my code before publishing

I was reading the the Android Publishing docs and they said to remove all Log calls from my code. I have some calls to e.printStackTrace() in my code that can be printed as part of the normal running of my program (ie. if a file does not exist yet).
Should I also remove these calls?
You shouldn't be using e.printStackTrace() directly anyway — doing so will send the info to the Android log without displaying which application (log tag) it came from.
As others have mentioned, continue to catch the Exception in question, but use one of the android.util.Log methods to do the logging. You could log only the message, but not the stack trace, or use verbose logging for the stack trace:
try {
Object foo = null;
foo.toString();
} catch (NullPointerException ex) {
Log.w(LOG_TAG, "Foo didn't work: "+ ex.getMessage());
Log.d(LOG_TAG, Util.stackTraceWriter(ex));
}
You should strip DEBUG or VERBOSE log messages from your production builds. The easiest way is to use ProGuard to remove Log.[dv] calls from your code.
If you allow an Exception to propagate up to the OS then the OS will log it and also pop up a Force Close window, killing your application. If you catch it, then you can prevent your application from being force closed.
If you want your users to have the ability to send you errors that they are getting, then I would log the stack trace. They can then send you the log via an app like Log Collector.
If you want to avoid the possibility of exposing your stack trace information to your users, then catch the exception and don't log it.
I would use Log class for message out put. For logs that you think are important to stay in the app - use Log.i
for errors warning - Log.e Log.w
For you debug Log.d - and that you can turnoff on base on if your application is in debug mode.
http://developer.android.com/reference/android/util/DebugUtils.html
Well printStackTrace() will log it into the OS, causing your andorid (or computer) app to terminate (force close), instead, do something like this:
public void nullPointerExceptionCauser()
{
try
{
Object example = null;
example.toString();
}
catch (Exception e)
{
Logger.log(Level.SEVERE, "Caught Exception: {0}", e.getStackTrace());
}
}
in my modest opinion (I'm not an Android developer)
It should be nice. I don't know the logging options for Android but I'm sure you have some configurable thing to output (or not) your traces.
And if you don't do printStackTrace() Android will not be doing the dirty work of ignoring it.
:)
It's only a good-feeling (style) thing.
If you want to be secure i.e. not allow anyone snooping to read exception logs you can do something like
private void hideExceptionsInReleaseMode()
{
final Thread.UncaughtExceptionHandler defaultHandler = Thread.getDefaultUncaughtExceptionHandler();
if(!BuildConfig.DEBUG)
{
Thread.setDefaultUncaughtExceptionHandler(new Thread.UncaughtExceptionHandler()
{
#Override
public void uncaughtException(Thread thread, Throwable ex)
{
defaultHandler.uncaughtException(thread, new RuntimeException("Something went wrong :p"));
}
});
}
}
In order to use printStackTrace in a safer way I would use StringWrite and PrintWriter:
...
catch (final Exception e)
{
final StringWriter sw = new StringWriter();
final PrintWriter pw = new PrintWriter(sw);
e.printStackTrace(pw);
Log.e("TAG", sw.toString());
}
Or alternatively:
catch (final Exception e)
{
Log.e(TAG, Log.getStackTraceString(e));
}
Use this to remove the logs from release apk
if (BuildConfig.DEBUG) Log.d(TAG, "your meseage");

Categories

Resources