请帮助我理解为什么:)我的程序到达"尝试"线,但似乎跳过" catch",虽然它打印了堆栈跟踪... 我在我的catch中使用了JOptionPane,但是System.out.println()也没有工作。 代码:
import java.awt.AWTException;
import java.awt.Rectangle;
import java.awt.Robot;
import java.awt.Toolkit;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import javax.imageio.ImageIO;
import javax.swing.JOptionPane;
public class main {
public static void main(String[] args) {
SimpleDateFormat dateFormat = new SimpleDateFormat("dd.MM.yyyy");
Calendar cal = Calendar.getInstance();
String fileName = dateFormat.format(cal.getTime());
Rectangle rectangle = new Rectangle(Toolkit.getDefaultToolkit().getScreenSize());
BufferedImage bufferedImage;
try {
bufferedImage = new Robot().createScreenCapture(rectangle);
try
{
ImageIO.write(bufferedImage, "jpg", new File("c:/temp/ScrenShots/"+fileName+".jpg"));
} catch (IOException e)
{
JOptionPane frame = null;
JOptionPane.showMessageDialog(frame,"Failed to take screen-shot", "ScreenShots", JOptionPane.ERROR_MESSAGE);
e.printStackTrace();
}
} catch (AWTException e) {
JOptionPane frame = null;
JOptionPane.showMessageDialog(frame,"AWT Error", "ScreenShots", JOptionPane.ERROR_MESSAGE);
e.printStackTrace();
}
}
}
例外:
java.io.FileNotFoundException: c:\temp\ScrenShots\20.10.2014.jpg (The system cannot find the path specified)
at java.io.RandomAccessFile.open(Native Method)
at java.io.RandomAccessFile.<init>(Unknown Source)
at javax.imageio.stream.FileImageOutputStream.<init>(Unknown Source)
at com.sun.imageio.spi.FileImageOutputStreamSpi.createOutputStreamInstance(Unknown Source)
at javax.imageio.ImageIO.createImageOutputStream(Unknown Source)
at javax.imageio.ImageIO.write(Unknown Source)
at main.main(main.java:26)
Exception in thread "main" java.lang.NullPointerException
at javax.imageio.ImageIO.write(Unknown Source)
at main.main(main.java:26)
答案 0 :(得分:2)
在NullPointerException
FileNotFoundException
从您的日志中。
Exception in thread "main" java.lang.NullPointerException //*
at javax.imageio.ImageIO.write(Unknown Source)
at main.main(main.java:26)
您可以通过以下方式确定。此代码仅用于指出问题。捕捉NullPointerException
是一种不好的编码习惯。
try {
// current code
} catch (IOException e) {
// current code
}catch (NullPointerException e){
JOptionPane frame = null;
JOptionPane.showMessageDialog(frame, "NPE", "npe", JOptionPane.ERROR_MESSAGE);
}