package com.age.www;
import java.util.InputMismatchException;
import java.util.Scanner;
class TryCatchDemo {
public static void main(String[] args) {
ThrowDemo td=new ThrowDemo();
System.out.println("请输入:");
Scanner input = new Scanner(System.in);
int res = 0;
try {
td.check(10);
int b = input.nextInt();
res = 10 / b;
//return; 即便加上return 从当前方法返回;仍然会执行finally里面的代码。如果这里写上System.exit(0),则整个程序停止,不再执行。
} catch (ArithmeticException e) {
e.printStackTrace();
} catch (InputMismatchException e) {
e.printStackTrace();
} catch (Exception e) { // 大哥负责压阵,如果try抛出一个异常对象,和上面的两个异常类型没有匹配的,则Exception接收,
// 因为Exception可以多态接收所有的子类Exception。
// System.exit(0);
System.out.println(e.getMessage());
e.printStackTrace();
} finally {
System.out.println("結果:" + res);
input.close();
}
System.out.println("結果2:" + res);
}
}
class ThrowDemo {
public void check(int age)throws Exception{
if(age<18){
throw new Exception("年龄不合格");
//受察异常(在编译的时候会检测的异常。非受察异常一般是指运行时异常,只有运行的过程中交互中发生异常。);抛出一个异常对象,如果抛出后必须对其进行捕获(try,catch语句);如果不捕获则必须抛出给调用者。
//就是在方法后面写上抛出throws Exception。调用者,在调用这个方法时必须捕获,或者继续抛出。
}
}
}
import java.util.InputMismatchException;
import java.util.Scanner;
class TryCatchDemo {
public static void main(String[] args) {
ThrowDemo td=new ThrowDemo();
System.out.println("请输入:");
Scanner input = new Scanner(System.in);
int res = 0;
try {
td.check(10);
int b = input.nextInt();
res = 10 / b;
//return; 即便加上return 从当前方法返回;仍然会执行finally里面的代码。如果这里写上System.exit(0),则整个程序停止,不再执行。
} catch (ArithmeticException e) {
e.printStackTrace();
} catch (InputMismatchException e) {
e.printStackTrace();
} catch (Exception e) { // 大哥负责压阵,如果try抛出一个异常对象,和上面的两个异常类型没有匹配的,则Exception接收,
// 因为Exception可以多态接收所有的子类Exception。
// System.exit(0);
System.out.println(e.getMessage());
e.printStackTrace();
} finally {
System.out.println("結果:" + res);
input.close();
}
System.out.println("結果2:" + res);
}
}
class ThrowDemo {
public void check(int age)throws Exception{
if(age<18){
throw new Exception("年龄不合格");
//受察异常(在编译的时候会检测的异常。非受察异常一般是指运行时异常,只有运行的过程中交互中发生异常。);抛出一个异常对象,如果抛出后必须对其进行捕获(try,catch语句);如果不捕获则必须抛出给调用者。
//就是在方法后面写上抛出throws Exception。调用者,在调用这个方法时必须捕获,或者继续抛出。
}
}
}