Android - print full exception backtrace to log - android

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()

Related

Cannot catch exception, catch block is never reached

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

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

Replace exception logging with custom error message

I'm using Android's httpclient to connect to a domain as follows:
try {
URL url = new URL("example.com");
HttpURLConnection conn = (HttpURLConnection)url.openConnection();
read(conn.getInputStream());
} catch (Exception e) {
e.printStackTrace();
}
Now is it fine if I remove this line:
e.printStackTrace();
And replace it with this:
Toast toast = Toast.makeText(getApplicationContext(), "Could not connect to domain.", Toast.LENGTH_LONG);
toast.show();
Or do I have to do something with the 'e' variable? In which case it'll be:
catch (Exception e) {
e.printStackTrace();
Toast toast = Toast.makeText(getApplicationContext(), "Could not connect to domain.", Toast.LENGTH_LONG);
toast.show();
}
And if I do e.printStackTrace(), where does it print to?
I'd recommend catching only the thrown exception type (I think IOException in this case). Other exceptions may be for completely unrelated problems.
Yes, it's fine to replace the printStackTrace with the toast. Bonus tip: Just call
Toast.makeText(getApplicationContext(), "Could not connect to domain.", Toast.LENGTH_LONG).show();
and you can do it all in one line. :)
e.printStackTrace() will print to the standard logcat trace, which you can view with the adb logcat command (adb is part of the Android SDK).

Why am I getting warnings Serialize ArrayList

I'm getting odd warnings in my reading of a ArrayList of Serializable objects. Here is the code:
public void loadBoard() {
FileInputStream fis = null;
ObjectInputStream is;
try {
fis = this.openFileInput(saveFile);
is = new ObjectInputStream(fis);
// Build up sample vision board
if (mVisionBoard == null) {
mVisionBoard = new ArrayList<VisionObject>();
} else {
mVisionBoard.clear();
}
ArrayList<VisionObject> readObject = (ArrayList<VisionObject>) is.readObject();
mVisionBoard = readObject;
is.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
Log.e(TAG, "loadBoard failed: "+e);
} catch (StreamCorruptedException e) {
e.printStackTrace();
Log.e(TAG, "loadBoard failed: "+e);
} catch (IOException e) {
e.printStackTrace();
Log.e(TAG, "loadBoard failed: "+e);
} catch (ClassNotFoundException e) {
e.printStackTrace();
Log.e(TAG, "loadBoard failed: "+e);
}
}
and the warning I'm getting is (on readObject line):
"Type safety: unchecked cast from Object to ArrayList"
The few examples I've read indicate that this is the correct code for reading an ArrayList of serializable objects. The code I made to write the arraylist isn't giving me any warnings. Am I doing something wrong here?
kind of late but it will help someone...
the reason of the warning is because of the return of the method readObject...
see:
public final Object readObject()
it returns actually an object
and if you just by mistake read and deserialize a lets say String object ant try to cast that into an array list then you will get a runtime execption (the reason must be obvious)
in order to avoid that predictable failure you can check the type of the returned object before the cast...
that is why you get the warning:
"Type safety: unchecked cast from Object to ArrayList<VisionObject>"

Android Internal Object Storage

I am trying to save ArrayLists(ArrayOne, ArrayTwo, and ArrayThree) of EditText's to the internal storage. As commented, it clearly shows that it attempts the save, but I never get another TOAST after that. Any help as of why it doesn't show "Save completed" or any error is appreciated.
public void save(Context c)
{
String fileName;
Toast.makeText(this, "Attempting Save", Toast.LENGTH_SHORT).show();//THIS SHOWS
if(semester.getText().toString().length() == 0)
{
Toast.makeText(c, "Please enter a filename", Toast.LENGTH_SHORT).show();
}
else
{
fileName = "test.dat";
FileOutputStream fos = null;
ObjectOutputStream oos = null;
try
{
fos = this.openFileOutput(fileName, Context.MODE_PRIVATE);
oos = new ObjectOutputStream(fos);
oos.writeObject(ArrayOne);
oos.writeObject(ArrayTwo);
oos.writeObject(ArrayThree);
Toast.makeText(c, "Save Completed", Toast.LENGTH_SHORT).show(); //THIS NEVER SHOWS
}
catch (FileNotFoundException e)
{
Toast.makeText(c, "Could not find " + fileName + " to save.", Toast.LENGTH_SHORT).show();
e.printStackTrace();
}
catch (IOException e)
{
e.printStackTrace();
}
finally
{
try
{
if (oos != null)
oos.close();
if (fos != null)
fos.close();
}
catch (Exception e)
{ /* do nothing */ }
}
}
}
The problem is that the EditText class is not serializable
If you debug and put a break point at on the printStackTrace and examine the IOException it will tell you that
catch (IOException e
{
e.printStackTrace();
}
Classes have to use "implements Serializable" in order for them to be written out as objects, which EditText does not have.
You can not extend the class and add the serializable tag either because the underlying class will still throw the exception.
I suggest you either serialize the data via your own class or save whatever you are trying to do with some other method.
I think the error is beings swallowed in your first Try block because you're only catching FileNotFound and IOException - just for debugging purposes you could catch the generic Exception and printout the stacktrace.
If it also helps this is what I do:
java.io.File file = new java.io.File("/sdcard/mystorage/ArrayOne.bin");
ObjectOutputStream out = new ObjectOutputStream(new BufferedOutputStream(new FileOutputStream(file)));
out.writeObject(obj);
out.close();
Best
-serkan
If nothing shows after the "Attempting save" you´re getting some exception in this block
catch (IOException e)
{
e.printStackTrace();
}
And you´re not viewing it in any Toast. Also you can be here in this way doing nothing with your exception:
catch (Exception e)
{ /* do nothing */ }
Instead of toasting your messages.. try to use LogCat for debbugging, is easy to use and also you don't need to put toast code in your code. Tell me how is going.

Categories

Resources