Java 错误:在相应的 try 语句的主体中永远不会抛出异常 IOException

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/19309108/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-12 15:56:21  来源:igfitidea点击:

error: exception IOException is never thrown in body of corresponding try statement

java

提问by GirlWhoCodes

I receive an error each time. What am I doing wrong?

我每次都会收到一个错误。我究竟做错了什么?

My Code:

我的代码:

 public static void hashMap(String crnString)
{
    try
    {
        if (mMap.containsKey(crnString))
        {
            int count = mMap.get(crnString);
            count++;
            mMap.put(crnString, count);
        }
        else
        {
            mMap.put(crnString, 1);
        }
    }
    catch (IOException e)
    {
        e.printStackTrace();
    }
    finally
    {
    }
}

采纳答案by Sotirios Delimanolis

Assuming mMapis a HashMap, the code inside the tryblock never throws an IOException. Remove the try-catchblock wrapping your code.

假设mMap是 a HashMaptry块内的代码永远不会抛出IOException。删除try-catch包装您的代码的块。

public static void hashMap(String crnString){
    if (mMap.containsKey(crnString)) {
        int count = mMap.get(crnString);
        count++;
        mMap.put(crnString, count);
    } else {
        mMap.put(crnString, 1);
    }
}

回答by Vallabh Patade

IOException is checked exception. So code in try block is not potential code that can raise IOExcption that's why the compiler shows error. Use specific exception type catch block that can be raised or use unchecked exception catch block. In you try block code, only NPE can be raised.

IOException 是检查异常。所以 try 块中的代码不是可能引发 IOExcption 的潜在代码,这就是编译器显示错误的原因。使用可以引发的特定异常类型 catch 块或使用未检查的异常 catch 块。在您尝试块代码时,只能引发 NPE。

  try
{
    if (mMap.containsKey(crnString))
    {
        int count = mMap.get(crnString);
        count++;
        mMap.put(crnString, count);
    }
    else
    {
        mMap.put(crnString, 1);
    }
} catch (NullPointerException e)
{
    e.printStackTrace();
} catch(Exception e) {
   System.out.println("Unexcepted Exception");
    e.printStackTrace();
}
finally
{
}