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:
Related
I newbie to Android development and I have a question.
I already look for this question in forum but no luck.
My MainActivity onCreate tries to connect to a sever.
In some cases the server can be down, and in this case, my app throw exception.
What should I do to finish the Activity gracefully?
I have tried to Toast a message and to finish() the activity but no message appears and the activity still running.
Whats wrong with my code ?
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
try {
mSocket = new Socket("127.0.0.1", 6000);
try {
conn = new ClientConnection(mSocket.getInputStream(),mSocket.getOutputStream());
GameSurfaceView gameSurface = (GameSurfaceView)findViewById(R.id.Game);
conn.start();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} catch (UnknownHostException e) {
Log.e(TAG, "Unknown Host Exception");
e.printStackTrace();
Toast.makeText(this, "Unknown Host Exception", Toast.LENGTH_SHORT);
finish();
} catch (IOException e) {
Log.e(TAG, "IO Exception");
Toast.makeText(this, "IO Exception", Toast.LENGTH_SHORT);
finish();
}
catch (Exception e) {
Log.e(TAG, "Exception");
Toast.makeText(this, "IO Exception", Toast.LENGTH_SHORT);
finish();
}
Log.v(TAG,"Activity created");
}
Don't ever run network code in the UI thread. onCreate is the UI thread - You should never do any IO, network or other long processing task there. Read http://developer.android.com/training/best-background.html for more details.
Your toast is in the catch clause of the out try block - however all IOExceptions (including the UnknownHostException) are already caught in the inner try block. In there you only print the stack trace. That's why no message is ever shown. I don't see a need for two nested try blocks, one is probably all you need.
Assuming your app cannot run without server connection, the right approach would be to let the user know somehow that that's the case (AlertDialog, Toast, whatever) and then call Finish() on the activity to close it.
Edit: As pointed out in a deleted answer, calling show() is of course also needed in top of what I already mentioned:
Toast.makeText(this, "Unknown Host Exception", Toast.LENGTH_SHORT).show();
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);
}
i tried out its not working anyone can help me out
public void googlefunc(View v)
{
try {
AddThis.shareItem(this, "googleplus", mUrl, mShareTitle,
mShareDescription);
}
catch (ATDatabaseException e) {
e.printStackTrace();
}
catch (ATSharerException e) {
e.printStackTrace();
}
}
You have to use google_plusone (or google_plusone_share) instead of googleplus.
See the list of the available service (and search for google_plusone to find the right row).
Up to Android 2.2 I know I can use reflection and terminate the call through getITelephony.
However, as of 2.3 this no longer works because even if you grant the MODIFY_PHONE_STATE permission to your app, it's now a system app only permission:
https://stackoverflow.com/a/5095956/821423
That said, it's possible still because a myriad of applications on the google play market are doing it just fine on ICS, for example, this one:
https://play.google.com/store/apps/details?id=com.androminigsm.fscifree&hl=en
So the question is, how do they do it? I know I can pick up the call using simulating a headset hook, but I can't figure out how to end the call.
Thank you.
Well after much soul-searching I realize something really, really, really dumb. On the plus side no one on StackOverflow seems to have noticed it either. MODIFY_PHONE_STATE is no longer working on silenceRinger() since 2.3+, but endCall is just fine.
So the solution is to comment out the call to silenceRinger().
Can't believe I've just spent a week on this! I'll try to update the other questions as there seem to be tons of dupe on SO along the lines of 'it's not possible to use reflection to terminate the calls anymore'.
The call() , endcall() functions work fine for me as well. But there is also another way tha works without using iTelephony.aidl. Its published in this post. BTW I think google already knows but for some reason they havent done anything with the rest of functions, wich is good!!!
http://androidbridge.blogspot.com/2011/05/how-to-answer-incoming-call-in-android.html
private void endCall(final String cutofftime) {
TelephonyManager telephony = (TelephonyManager) srvs
.getSystemService(Context.TELEPHONY_SERVICE);
Class c;
final com.android.internal.telephony.ITelephony telephonyService;
try {
c = Class.forName("android.telephony.TelephonyManager");//telephony.getClass().getName());
Log.i("TelephonyClass Name", telephony.getClass().getName());
Method m = c.getDeclaredMethod("getITelephony");
m.setAccessible(true);
telephonyService = (ITelephony) m.invoke(telephony);
TimerTask task = new TimerTask() {
#Override
public void run() {
try {
if (telephonyService.isIdle()
|| telephonyService.isOffhook()
|| telephonyService.isRinging())
telephonyService.endCall();
} catch (RemoteException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
};
long delay = Integer.parseInt(cutofftime) * 1000;
new Timer().schedule(task, delay);
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (SecurityException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (NoSuchMethodException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalArgumentException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalAccessException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (InvocationTargetException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
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