包括try catch块后甚至出现IO异常

时间:2018-05-30 08:32:40

标签: android

以下代码正在创建错误

Activity context;
context = new Activity();
try {
    InputStream configAsset = context.getApplicationContext().getAssets().open("MyConfig.cfg");
    //SimpleSpkDetSystem alizeSystem = new SimpleSpkDetSystem(configAsset, context.getApplicationContext().getFilesDir().getPath());

}catch (FileNotFoundException e) {
    Log.e(LOG_TAG, "File not found for recording ", e);
}

错误:

Error:(255, 87) error: unreported exception IOException; must be caught or declared to be thrown
Error:Execution failed for task ':app:compileDebugJavaWithJavac'.
> Compilation failed; see the compiler error output for details.

即使我加入了try,catch阻止了为什么会产生错误?

3 个答案:

答案 0 :(得分:2)

更改您的代码:

在:

Activity context;
        context = new Activity();
        try {
            InputStream configAsset = context.getApplicationContext().getAssets().open("MyConfig.cfg");
            //SimpleSpkDetSystem alizeSystem = new SimpleSpkDetSystem(configAsset, context.getApplicationContext().getFilesDir().getPath());

        }catch (FileNotFoundException e) {
            Log.e(LOG_TAG, "File not found for recording ", e);
        }

在:

Activity context;
        context = new Activity();
        try {
            InputStream configAsset = context.getApplicationContext().getAssets().open("MyConfig.cfg");
            //SimpleSpkDetSystem alizeSystem = new SimpleSpkDetSystem(configAsset, context.getApplicationContext().getFilesDir().getPath());

        }catch (IOException e) {
            Log.e(LOG_TAG, "File not found for recording ", e);
        }

答案 1 :(得分:2)

试试这个,FileNotFoundExceptionIOException的父级。因此,捕获IOException将确保您捕获作为Activity context; context = new Activity(); try { InputStream configAsset = context.getApplicationContext().getAssets().open("MyConfig.cfg"); //SimpleSpkDetSystem alizeSystem = new SimpleSpkDetSystem(configAsset, context.getApplicationContext().getFilesDir().getPath()); }catch (IOException e) { Log.e(LOG_TAG, "File not found for recording ", e); } 的子类的任何异常。

./ byfn.sh -m up

答案 2 :(得分:0)

您应该包含以下内容以避免崩溃,

        try {
            InputStream configAsset =getApplication().getAssets().open("MyConfig.cfg");               
        }catch (FileNotFoundException e) {
            Log.e("ddsa", "File not found for recording ", e);
        } catch (IOException e) {
            Log.e("ddsa", "IOException  ", e);
            e.printStackTrace();
        } 

你设置的上下文也不适合我,这就是getApplication()

的原因