try-catch-finally throws throw示例

68 阅读1分钟

try-catch-finally实例

public class ExcepTest{  
    public static void main(String args[]){  
        try{  
            System.out.println("异常发生前");  
            int a[] = new int[2];  
            System.out.println("异常发生时 :" + a[3]);  
        } catch (ArrayIndexOutOfBoundsException e){  
            System.out.println("捕获异常 :" + e);  
        } finally {  
            System.out.println("finally 发生");  
        }  
        System.out.println("处理结束");  
    }  
}

运行结果 屏幕截图 2024-01-25 092857.png

throws实例

static void readFile(String filePath) throws IOException {  
    BufferedReader reader = new BufferedReader(new FileReader(filePath));  
    String line = reader.readLine();  
    while (line != null) {  
        System.out.println(line);  
    line = reader.readLine();  
    }  
    reader.close();  
}  
  
public static void main(String[] args) throws IOException {  
    readFile("D://a.txt");  
}

运行结果

3.png

throw实例

public class MyClass {
    static void checkAge(int age) { 
        if (age < 18) {
            throw new ArithmeticException("年龄小于18"); 
        } else {
            System.out.println("年龄大于18"); 
        }
     } 
     public static void main(String[] args) {
         checkAge(15); 
     } 
}

运行结果

屏幕截图 2024-01-24 125209.png