如何从Exception获取消息?

时间:2013-08-26 11:58:49

标签: android

以下是我的代码:\

public void LoadProjectFile(String Filename) throws Exception
{
  //  m_Renderer.m_Project=new Project();
   refresh_project();
    m_Renderer.m_SelectedProjectPath =  Filename;

    try {
        m_Renderer.m_Project.load_file(Filename);

    }
    catch (Exception e)

    {
        //Exception a = e.getMessage();
        String a= e.getMessage();

        throw new Exception(a);
    }

    //AppFuncs.m_GisProject=m_Renderer.m_Project;

}



        try
        {

            Map.this.mGLView.LoadProjectFile(AppFuncs.g_path);
             Map.this.mGLView.requestRender();
    }
        catch (Exception e)
        {
            br=1;
             b=e.getMessage();
        }

加载项目文件会抛出一个我在Map类中收到的异常。 This exception contains message: Java.lang.exception: java.lang.exception: file not found.

我只想显示"File not found"条消息。那么如何从异常中获取此消息呢?

2 个答案:

答案 0 :(得分:0)

捕获所有类型的异常而不是基本异常:

try {
    m_Renderer.m_Project.load_file(Filename);

}
catch (FileNotFoundException e)
{
    String a= "File not found"
    throw new Exception(a);
}
catch (SomeOhterException e){ 
    String a= "Some other message"
    throw new Exception(a);
}
//at the end, but it shouldn't be necessary 
catch (Exception e){ 
    String a= "Something happend we don't know what"
    throw new Exception(a);
}

很快:对于不同的异常使用不同的类来显示比使用异常消息更正确的信息。

答案 1 :(得分:0)

抓住FileNotFoundException而不是Exception

例如:

try {
      //whatever
} catch (FileNotFoundException e) {
      System.out.println("File not found");
}