不,我们不能在try,catch和finally块之间编写任何语句,这些块形成一个单元。try关键字 的功能是识别异常对象并捕获该异常对象,然后通过挂起try块的执行,将控件与已标识的异常对象一起转移到catch块。catch块的功能是接收try和catch异常类对象发送的异常类对象,并将该异常类对象分配给catch块中定义的相应异常类的引用。。该finally块小号是其要得到强制不论异常的执行块。
我们可以编写诸如try with catch block的语句,尝试多个catch块,try的finally块,try的catch和finally块的语句,并且不能在这些组合之间编写任何代码或语句。如果我们尝试在这些块之间放置任何语句,则将引发编译时错误。
语法try
{
//监视异常的语句
}// We can't keep any statements herecatch(Exception ex){
//在这里捕获异常
}// We can't keep any statements herefinally{
//finally块是可选的,并且只有在try或try-catch块存在的情况下才能存在。
//无论try块中是否发生异常,始终执行此块
//并且是否在catch块中捕获了发生的异常。
//如果仅发生System.exit()且没有发生任何错误,则不会仅执行finally块。
}
示例public class ExceptionHandlingTest {
public static void main(String[] args) {
System.out.println("We can keep any number of statements here");
try {
int i = 10/0; // This statement throws ArithmeticException
System.out.println("This statement will not be executed");
} //We can't keep statements here catch(ArithmeticException ex){
System.out.println("This block is executed immediately after an exception is thrown");
} //We can't keep statements here finally {
System.out.println("This block is always executed");
}
System.out.println("We can keep any number of statements here");
}
}
输出结果We can keep any number of statements here
This block is executed immediately after an exception is thrown
This block is always executed
We can keep any number of statements here