简体   繁体   English

即使发生异常,如何继续执行程序?

[英]How do you continue your program even if an exception occurs?

In my program I have to constantly access the hard drive thousands of times to view images (no way around it), occasionally my program gets tripped up on a "file not found IO Exception" most likely because of the many modifications I'm making to the images and re saving quickly. 在我的程序中,我必须不停地访问硬盘数千次以查看图像(无法绕开它),偶尔,由于我进行了许多修改,我的程序有时因“文件未找到IO异常”而跳闸并重新保存图像。 How do I continue my program even if this error occurs, because currently it causes my program to stop? 即使发生此错误,因为当前它导致我的程序停止,如何继续执行我的程序?

Code: 码:

filepattern=imageLocation+temp+"image.jpg";
File outputfile = new File(filepattern);

BufferedImage img = null;
try {
    img = ImageIO.read(outputfile);
} catch (IOException e) {
}                 

Note: I have fixed the problem by making sure the file exists first. 注意:我已经通过确保文件首先存在来解决此问题。 Thanks for all your help! 感谢你的帮助!

Catch the exception and handle it as needed. 捕获异常并根据需要进行处理。

try {

// your code

} catch (<Expected exception> e) {
// handle the exception
}

Surround the statement with a try catch . try catch包围语句。

This will stop the code from crashing and in the catch block you can write code to deal with the failure. 这将防止代码崩溃,并且在catch块中,您可以编写代码来处理故障。

There are 3 key words try {} executes the block that can cause problems catch (Exception ex) {} executes code to handle specific exceptions. 有3个关键字try {}执行可能导致问题捕获的块(异常ex){}执行代码以处理特定的异常。 Instead of Exception you can handle specific exception types finally {} executes cleanup code. 最终,您可以处理特定的异常类型来代替Exception {}执行清除代码。 Even if exception occurs and breaks the execution flow in try block, this code will always execute. 即使发生异常并破坏try块中的执行流程,该代码也将始终执行。

You might try something like the fragment below. 您可以尝试以下片段。 Of course, you will want to encapsulate the actual reading in a try / catch / finally block to make sure you close the file 当然,您需要将实际的读数封装在try / catch / finally块中,以确保关闭文件

try {
    filesTried++;
    [you code]
} catch (IOException e) {
    fileErrors++;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM