3 回答

TA贡献1805条经验 获得超10个赞
在其中,java您将获得很多,Exceptions并且您必须使用try..catchblock来处理它。
try{
//code that may throw exception
}catch(Exception_class_Name ref){}
另外,您必须boolean x 在try块之外进行定义,并且应将其初始化为某个值(true或false)。
尝试以下代码:-
import java.io.File;
public class Main {
public static void main(String[] args) {
File myArchive = new File("MyDocument.txt");
boolean x = true;
try {
x = myArchive.createNewFile();
} catch (Exception e) {
e.printStackTrace();
}
System.out.println(x);
}
}
输出:-
true

TA贡献1891条经验 获得超3个赞
只是一个尝试捕获的介绍,它的用途是:
某些操作可能会产生错误,甚至可能不是程序员的错误,但可能由于不可预见的情况而发生。
例如,您要创建一个文件,但是此时,文件目的地可能不存在(例如,取出了USB记忆棒),或者光盘可能已满,或者文件名可能无效(由另一个用户提供)通过键盘(包含“禁止”字符)进行操作,或者可能未授予权限(例如,在Android中,当您的手机要求写入文件的权限时,您可以授予它,或者出于安全考虑而拒绝授予它)。
对于这种情况,Java为您提供了尝试容易出错的代码,然后捕获错误的机会。如果发生错误,则不希望您的应用崩溃。您希望它继续继续工作,因此您可以在屏幕上警告用户该文件操作失败,并提供其他操作。
因此,基本上,您可以执行以下操作
try{
// place a risky part of code here
// like, creating a file
} catch (Exception error)
{
// This part will be executed only if there is an error
// in this part, you can change the wrong file name
// or tell the user that the disc is not available
// just do something about the error.
// If an error does not occur, then this part will not be executed.
}

TA贡献1803条经验 获得超3个赞
try {
boolean x = myArchive.createNewFile();
System.out.println(x);
} catch (IOException e) {
e.printStackTrace();
}
try块包含可能发生异常的语句集。在try块之后始终是catch块,该catch块处理在关联的try块中发生的异常
添加回答
举报