Cannot catch exception, catch block is never reached - android

I have code structurred in this way
public void generalMethod(){
try{
methodThatStartAsyncWebTask();
catch(Exception e){
offlineDataAlternativeMethod();
}
}
the method
public void offlineDataAlternativeMethod(){
try(
loadArchivedFile();
}
catch(Exception e){
reInitializeeData();
}
}
The App crashes at line loadArchivedFile(); that fails because doesn't found the file, but the strange thing is that catch block that invokes reInitializeeData(); isn't reached.
Why cannot reach catch block in anyway? Any idea?
This is the first time that see a similar issue. Any solution?

Try this
getting file not found exception

Related

catch only ENOSPC on Android

This might be a basic question but I cannot find an answer. When you want to catch only FileNotFound in Android, then you write
} catch (FileNotFoundException e) {
But what do you write if you want to catch exactly ENOSPC (No space left on device) errors? I can't use "catch (Exception e)" because I want to explicitly deal with this one error.
You cannot do so directly as enospc is signaled as a java.io.IOException which will catch many other io related issues as well. But by looking up the cause and the error it's signalling you can zoom in and handle enospc exceptions but rethrow all others, like this:
} catch (IOException ex) {
boolean itsanenospcex = false;
// make sure the cause is an ErrnoException
if (ex.getCause() instanceof android.system.ErrnoException) {
// if so, we can get to the causing errno
int errno = ((android.system.ErrnoException) ex.getCause()).errno;
// and check for the appropriate value
itsanenospcex = errno == OsConstants.ENOSPC;
}
if (itsanenospcex) {
// handle it
} else {
// if it's any other ioexception, rethrow it
throw ex;
}
}
Sidenote: } catch (Exception e) { is generally considered bad practice.

How do i display the catch exception?

I just want to ask how do i display the catch exception in android so that i will know if my application catching some error..
example on this.
try {
my codes here.....
} catch (IOException e) {
//how do i dpslay the exception
}
Thank you in advance.
I guess you want some visual (UI) representation of errors.
You can display your errors with Toast, for example.
Or use some library like Crouton. See http://johnkil.github.io/Android-AppMsg/
you can use:
try {
// my codes here.....
} catch(IOException e){
Log.d("MY_APP", "---------------------"); //separator from other logs (optional)
e.printStackTrace();
Log.d("MY_APP", "---------------------"); //separator from other logs (optional)
}
You can use Toast class for instance:
...
catch (IOException e) {
Toast.makeText(<context>, e.getMessage(), Toast.LENGHT_LONG).show();
// or use Log class like Log.e("From class X", e.getMessage());
}
Note if that piece of code is invoked from background Thread you cannot show that message for that that Thread.
In this scenario you need to use another mechanism (runOnUiThread(), Handler, AsyncTask, etc.).
Try doing this...This might help you..
try {
my codes here.....
} catch (IOException e) {
Log.e("e", "exception", e);
}

HttpHostConnectException - How can I catch it right?

I have a HttpHostConnectException... That is okay, because the server is offline. So I want to mange to catch this exception for the situation, the server will be down.
But if I use
catch (HttpHostConnectException e){
e.printStackTrace();
}
Nothing happens and the exception will be kill the progess. So how can I catch "unreachable" servers? Thank your for your time and help ;)
Calling e.printStackTrace(); will Kill your app as the exception is not handled
e.printStackTrace(); will print the exception on to the logcat and Will show an error or will crash you app
Either you can display the exception as string or Make static text as toast saying server unreachable
catch (HttpHostConnectException e)
{
Toast.makeText(getApplicationContext(), "Server Unreachable ", Toast.LENGTH_LONG).show();
}
if you want to show what was the actual problem / exception that was caused use
catch (HttpHostConnectException e)
{
Toast.makeText(getApplicationContext(), "Connection Timeout Reason "+string.ValueOf(e), Toast.LENGTH_LONG).show();
}
By doing this your app will not kill itself and proceed to the next line of your code
you can also do this
Log.v(locat, exception.toString());

How to prevent android app from crashing when a file has not been found using openFileInput

I want to react to a situation that no file has been found using FileInputStream. When i ran an app that loads a file that doesn't exist it opens an android popup with force close. I would like to react to the situation by changing a text in a text view and saying that the file has not been found. i tried changing the exceptions to change a text view and show that a file has not been found and the app still crashes.
Here is the piece of code:
FileInputStream fis = null;
String collected = null;
try {
fis = openFileInput("test");
byte[] dataArray = new byte[fis.available()];
while (fis.read(dataArray) != -1){
collected = new String(dataArray);
}
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally{
try {
fis.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
tv.setText(collected);
To ensure that an Android application does not force-close, your options are: a) do not do anything that will cause an exception, b) catch your exception with your own try/catch block, c) install an application level uncaught exception handler. Option a is not too feasible, c is not very helpful, and based on your code snippet you seem to be trying b -- however there appears to be another exception that you're not catching with this. The contents of logcat will tell you what exception, and the stack trace will lead to a point in your code which needs the try/catch.

Android - print full exception backtrace to log

I have a try/catch block that throws an exception and I would like to see information about the exception in the Android device log.
I read the log of the mobile device with this command from my development computer:
/home/dan/android-sdk-linux_x86/tools/adb shell logcat
I tried this first:
try {
// code buggy code
} catch (Exception e)
{
e.printStackTrace();
}
but that doesn't print anything to the log. That's a pity because it would have helped a lot.
The best I have achieved is:
try {
// code buggy code
} catch (Exception e)
{
Log.e("MYAPP", "exception: " + e.getMessage());
Log.e("MYAPP", "exception: " + e.toString());
}
Better than nothing but not very satisfying.
Do you know how to print the full backtrace to the log?
Thanks.
try {
// code that might throw an exception
} catch (Exception e) {
Log.e("MYAPP", "exception", e);
}
More Explicitly with Further Info
(Since this is the oldest question about this.)
The three-argument Android log methods will print the stack trace for an Exception that is provided as the third parameter. For example
Log.d(String tag, String msg, Throwable tr)
where tr is the Exception.
According to this comment those Log methods "use the getStackTraceString() method ... behind the scenes" to do that.
This helper function also works nice since Exception is also a Throwable.
try{
//bugtastic code here
}
catch (Exception e)
{
Log.e(TAG, "Exception: "+Log.getStackTraceString(e));
}
catch (Exception e) {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
PrintStream stream = new PrintStream( baos );
e.printStackTrace(stream);
stream.flush();
Log.e("MYAPP", new String( baos.toByteArray() );
}
Or... ya know... what EboMike said.
public String getStackTrace(Exception e){
StringWriter sw = new StringWriter();
PrintWriter pw = new PrintWriter(sw);
e.printStackTrace(pw);
return sw.toString();
}
e.printStackTrace() prints it to me. I don't think you're running the logcat correctly. Don't run it in a shell, just run
/home/dan/android-sdk-linux_x86/tools/adb logcat
The standard output and error output are directed to /dev/null by default so it is all lost. If you want to log this output then you need to follow the instructions "Viewing stdout and stderr" shown here
try{
...
} catch (Exception e) {
Log.e(e.getClass().getName(), e.getMessage(), e.getCause());
}
if you want to print out stack trace without exception, you can create it by following command
(new Throwable()).printStackTrace();
In the context of Android, I had to cast the Exception to a String:
try {
url = new URL(REGISTRATION_PATH);
urlConnection = (HttpURLConnection) url.openConnection();
} catch(MalformedURLException e) {
Log.i("MALFORMED URL", String.valueOf(e));
} catch(IOException e) {
Log.i("IOException", String.valueOf(e));
}
KOTLIN SOLUTION:
You can make use of the helper function getStackTraceString() belonging to the android.util.Log class to print the entire error message on console.
Example:
try {
// your code here
} catch (e: Exception) {
Log.e("TAG", "Exception occurred, stack trace: " + e.getStackTraceString());
}
Kotlin extension. Returns the detailed description of this throwable with its stack trace.
e.stackTraceToString()

Categories

Resources