eg1:
执行主函数,执行m()方法,进入m()静态方法,抛出异常,throw下面的语句不会再执行,不管是否抛出异常或者是否catch到,都会执行finally语句,然后程序离开这个try.........finally语句块,回到调用方法的地方,于是这一情况相当于在调用f()的那一行throw了一个exception,catch捕捉到异常并处理,然后继续执行catch下面的语句
package practice4;
public class B {
public static void m() throws Exception{
try{
throw new Exception();
}finally{
System.out.println("1");
}
}
public static void main(String[] args) {
try{
m();
}catch(Exception e){
System.out.println("2");
}
System.out.println("3");
}
}
输出:
1
2
3
eg2:设计一个程序,定义一个StringToolLongException异常,表示一个String对象的长度太长。在main中,让用户输入一个字符串,一直到程序被终止。如果读入的字符串超过20哥字符,就抛出这个异常。
package practice4;
import java.util.Scanner;
class StringToolLongException extends Exception{}
public class C {
public static void main(String[] args) throws StringToolLongException{
Scanner scan=new Scanner(System.in);
while(scan.hasNext()){
String s=scan.nextLine();
try{
if(s.length()>20){
throw new StringToolLongException();
}
else{
System.out.println(s);
}
}catch(StringToolLongException e){
e.printStackTrace();
}
}
}
}