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).
Related
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);
}
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());
My android aplication tries to connect to a service using
response = client.execute(getRequest);
However the server might be down and at such times I would like to throw a custom exception with a custom message, rather than the message android provides, saying the application has shut down unexpectedly.
Is there any way to do this?
try
{
response = client.execute(getRequest);
}
catch(Exception ex)
{
// Or add your custom exception here
Log.e("Your Custom Message:",ex.toString());
}
You can try wrapping the call in a try-catch block, and catch the generic Exception type, then process it (see if the server is down), then throw your custom exception.
try
{
response = client.execute(getRequest);
}
catch(Exception e)
{
//processing
throw new MyCustomException();
}
Write your own class MyException extends Exception{... and give some custom implementation to it. That can be in the constructor of that class or in some method.
And throw it like -
try{
response = client.execute(getRequest);
}catch(Exception e){
//handle your exception
throw new MyException();
}
If you also wish to show this custom message to the user, you can do so this way:
try {
response = client.execute(getRequest);
} catch(Exception e) {
Toast.makeText(getApplicationContext(), "My custom message", Toast.LENGTH_LONG).show();
throw new Exception("My custom message", e);
}
Can you print the e.printstacktrace(); in exception block?
I think there you will get details on what type of exception you are getting.
I solved this problem using ACRA
http://code.google.com/p/acra/wiki/BasicSetup
http://code.google.com/p/acra/wiki/AdvancedUsage
You can overwrite the default crash report and display a custom toast instead using
#ReportsCrashes(formKey="dGVacG0ydVHnaNHjRjVTUTEtb3FPWGc6MQ",
mode = ReportingInteractionMode.TOAST,
forceCloseDialogAfterToast = false, // optional, default false
resToastText = R.string.crash_toast_text)
I noticed that a toast isn't displayed when it's used inside a catch block.
Does anyone know how to show toasts when catching exceptions? An Example:
try {
// try to open a file
} catch (FileNotFoundException e) {
Toast.makeText(this, R.string.txt_file_not_found, Toast.LENGTH_LONG);
return; // cancel processing
}
Should be like this:
Toast toast = Toast.makeText(this, R.string.txt_file_not_found, Toast.LENGTH_LONG);
toast.show();
Yes, I put it right behind the existing line:
Toast.makeText(this, R.string.txt_file_not_found, Toast.LENGTH_LONG).show();
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()