安卓异常处理



我在处理方法调用的异常时遇到问题。我正在尝试做的是在捕获异常时创建一个警报对话框(我知道如何创建警报对话框)。引发异常的方法位于不同的类中,这就是为什么在捕获异常时无法创建警报对话框的原因。见下文:-

protected Boolean doInBackground(final String... args) { 
    try{
        ParserLive parser = new ParserLive();
        feeds = parser.parse(); // this is the method throwing the exception
        return true;  //won't return true because it gets stuck here
    } catch (Throwable t){
        return false;
    }    
} 

下面是ParserLive类,其中的方法如下:

public class ParserLive {
       //variables and constructor
       //Below is the method I want to handle
       //Ideally I'd like to wrap the code inside this method with a try-catch, 
       //and put the dialog in the catch statement, but this is not allowed.
       public List<Feed> parse() {
       //some code 
       // the following code is throwing the error, when I try to create an alert dialog inside this catch statement it says "the constructor AlertDialog.Builder(ParserLive) is undefined"
       try {
            Xml.parse(this.getInputStream(), Xml.Encoding.UTF_8, root.getContentHandler());
       } catch (Exception e) {
             throw new RuntimeException(e); 
         }
     return feeds;
  }
}

编辑

我已经编辑了上面的代码,以包含 LogCat 中抛出以下错误的代码行 - " java.lang.RuntimeException: org.apache.harmony.xml.ExpatParser$ParseException: 在第 1 行,第 0 列:未找到元素"

        protected Boolean doInBackground(final String... args) { 
            try{
                ParserLive parser = new ParserLive();
                feeds = parser.parse(); 
                return true;  
            } catch (Exception e){
                log.d("Error", e.getMessage());
                yourActivity.runOnUiThread(new Runnable() {
                                  public void run() {
                                      Toast.makeText(context, e.getMessage(), 3000).show();        }
                                 });
//Here you can create dialog also
                return false;
            }    
        }

最新更新