[英]java.io.IOException when declaring path to log file
I'm trying to log to a file in Java, so I looked here and wrote the following code: 我试图登录到Java文件,所以我在这里看了下面的代码:
private static final Logger log = Logger.getLogger( QualityGatesProvider.class.getName() );
//some other code
FileHandler fh = new FileHandler("/Users/me/.jenkins/myLogs");
log.addHandler(fh);
However, on the line FileHandler fh = new FileHandler("/Users/me/.jenkins/myLogs");
但是,在
FileHandler fh = new FileHandler("/Users/me/.jenkins/myLogs");
, I get this: ,我得到这个:
unreported exception java.io.IOException; must be caught or declared to be thrown
Any idea what could be wrong with the code? 知道代码有什么问题吗?
java.io.IOException is a checked exception . java.io.IOException是一个已检查的异常 。 Therefore, any line that could throw it must be either:
因此,任何可能抛出它的行都必须是:
.-Included in a try-catch block that captures it. .-包含在捕获它的try-catch块中。
try{
...
FileHandler fh = new FileHandler("/Users/me/.jenkins/myLogs");
...
} catch (java.io.IOException e){
//handle exception
}
.-Included in a method that throws it explicitly. .-包含在显式抛出它的方法中。
void myMethod() throws java.io.IOException{
...
FileHandler fh = new FileHandler("/Users/me/.jenkins/myLogs");
...
}
You will need to write this code inside a block: 您将需要在一个代码块中编写以下代码:
log.addHandler(fh);
It cannot be directly placed in the body of a class
along with other class member declarations. 它不能与其他类成员声明一起直接放置在
class
的主体中。
Put it inside a method like this: 将其放入这样的方法中:
public void foo() {
log.addHandler(fh); // this will still give a compilation error
}
To solve the compilation error, 为了解决编译错误,
Declare the method to throw the exception or handle it right inside the method. 声明方法以引发异常或在方法内部对其进行处理。
public void foo() throws Exception{
log.addHandler(fh);
}
OR 要么
public void foo() {
try{
log.addHandler(fh);
} catch (Exception e){
e.printstacktrace();
// OR handle exception here
}
}
Hope this helps! 希望这可以帮助!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.