Reputation: 173
I'm coding an android application must catch in the main activity all throwed exceptions and send email to me. But in some areas in my application i can't just throw the exception by the method :
Example : onCreateDialog() in a custom DialogFragment :
builder.setView(addCatLayout)
// Add action buttons
.setPositiveButton(R.string.button_ok,
new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int id) {
try {
// Save some data in DB here
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
dialog.dismiss();
}
})
.setNegativeButton(R.string.button_cancel,
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
// Close the dialog window
dialog.dismiss();
}
});
return builder.create();
My question how can i remove try catch block from this method and throw directly the exception to be catched in my main activity ? I want to have only one try catch block in the main activity that's catch all exceptions and sends mail to me. It's this possible ?
Thank you !
Upvotes: 0
Views: 1561
Reputation: 17105
If you create the dialog in activity and want to handle the Exception there
activity:
protected void handleException(Exception e) {
e.printStackTrace();
}
OnClick:
@Override
public void onClick(DialogInterface dialog, int id) {
try {
// Save some data in DB here
} catch (Exception e) {
// TODO Auto-generated catch block
handleException(e); // methods are visible to nested classes
}
dialog.dismiss();
}
If you are creating the dialog outside activity, then you should
public void handleException(Exception e) {
e.printStackTrace();
}
Dialog creating class
public static void createDialog(final YourActivity activity) {
....
@Override
public void onClick(DialogInterface dialog, int id) {
try {
// Save some data in DB here
} catch (Exception e) {
activity.handleException(e);
}
dialog.dismiss();
}
}
But that way it is a better practice to make your Activity implement some interface, like
public final class YourActivity implements ExceptionHandler {
Where the Exception handler is
public interface ExceptionHandler {
void handleException(Exception e);
}
And pass the Exception handler interface
public void createDialog(final ExceptionHandler handler) {
Upvotes: 1