views:

363

answers:

2

I'm a newbie Android developer. I would like to know if there exists a way to listen for a custom exception in Android and display its text using an alert. Thank you.

+3  A: 

Just catch the desired exception, then create a new AlertDialog containing the contents of the exception.

import android.app.Activity;
import android.app.AlertDialog;
import android.os.Bundle;

public class HelloException extends Activity {
    public class MyException extends Exception {
     private static final long serialVersionUID = 467370249776948948L;
     MyException(String message) {
         super(message);
     }
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
    }

    @Override
    public void onResume() {
        super.onResume();
        try {
            doSomething();
        } catch (MyException e) {
            AlertDialog.Builder dialog = new AlertDialog.Builder(this);
            dialog.setTitle("MyException Occured");
            dialog.setMessage(e.getMessage());
            dialog.setNeutralButton("Cool", null);
            dialog.create().show();
        }
    }

    private void doSomething() throws MyException {
        throw new MyException("Hello world.");
    }
}
Trevor Johns
Thanks, this solved my problem.
bodom_lx
A: 

Just for letting other users know: If you've got a separated custom exception that you wish to use everywhere (models, controllers etc.), and also in your views, propagate the custom exception everywhere and add Trevor's AlertDialog code in a method defined in your exception, passing it the context:

package it.unibz.pomodroid.exceptions;

import android.app.AlertDialog;
import android.content.Context;

public class PomodroidException extends Exception{
    /**
     * 
     */
    private static final long serialVersionUID = 1L;

    // Default constructor 
    // initializes custom exception variable to none
    public PomodroidException() {
        // call superclass constructor
        super();            
    }

    // Custom Exception Constructor
    public PomodroidException(String message) {
        // Call super class constructor
        super(message);  
    } 


    public void alertUser(Context context){
        AlertDialog.Builder dialog = new AlertDialog.Builder(context); 
        dialog.setTitle("WARNING");
        dialog.setMessage(this.toString());
        dialog.setNeutralButton("Ok", null);
        dialog.create().show();
    }

}

In my snippet, the method is alertUser(Context context). To display the Alert in an Activity, simply use:

try {
    // ...
} catch (PomodroidException e) {
    e.alertUser(this);
}

It's very easy to overload the method to customize some parts of the AlertDialog like its title and the text of the button.

Hope this helps someone.

bodom_lx