Java 类中的错误“必须捕获或声明要抛出未报告的异常 java.io.ioexception”
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/25577398/
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
Error "unreported exception java.io.ioexception must be caught or declared to be thrown" in Java class
提问by Surz
I am getting a "unreported exception java.io.ioexception must be caught or declared to be thrown" for some reason. I throw an I/O exception in this method:
由于某种原因,我收到“必须捕获或声明要抛出的未报告异常 java.io.ioexception”。我在这个方法中抛出一个 I/O 异常:
private void setChar() throws IOException
{
try
{
int data = in.read();
if(data==-1)
{
eof = true;
}
else
{
currentChar = (char) data;
}
}
catch (IOException e)
{
System.exit(0);
}
}
And I call the method here (in the constructors):
我在这里调用方法(在构造函数中):
private BufferedReader in;
private char currentChar;
private boolean done;
public Scanner(InputStream inStream)
{
in = new BufferedReader(new InputStreamReader(inStream));
done = false;
getNextChar();
}
public Scanner(String inString)
{
in = new BufferedReader(new StringReader(inString));
done = false;
setChar();
}
Am I calling / throwing the exception wrong?
我调用/抛出异常错误吗?
回答by chiastic-security
Your Scanner
constructor can throw an IOException
, because it's calling setChar()
, and that can throw it.
您的Scanner
构造函数可以抛出IOException
,因为它正在调用setChar()
,并且可以抛出它。
You must either declare your constructor as throwing the exception, or catch the exception in your constructor and deal with it.
您必须将构造函数声明为抛出异常,或者在构造函数中捕获异常并处理它。
回答by DaveH
Your setChar()
method says that it can throw an IOException, but your second constructor does not handle it.
您的setChar()
方法说它可以抛出 IOException,但您的第二个构造函数不处理它。
You either need to change the setChar() methods signature to not throw the exception (as, in fact, it doesn't throw an IOException), or get you constructor to handle it, for example ...
您要么需要更改 setChar() 方法签名以不抛出异常(因为,实际上,它不会抛出 IOException),或者让您的构造函数来处理它,例如...
public Scanner(String inString)
{
in = new BufferedReader(new StringReader(inString));
done = false;
try {
setChar();
}
catch (IOException ie){
System.exit(1)
}
}
回答by R2B2
setChar();
in your constructor throws an IOException
.
setChar();
在您的构造函数中抛出一个IOException
.
Therefore, you must catch it in your constructor, or your constructor have to throw an IOException
as well.
因此,您必须在构造函数中捕获它,否则您的构造函数也必须抛出 an IOException
。
However, you don't even need to add throws IOException
after the declaration of the setChar()
method since you are catching potential exceptions inside it.
但是,您甚至不需要throws IOException
在setChar()
方法声明之后添加,因为您正在捕获其中的潜在异常。