Discuss / Java / 在这个程序中最后既可以 throw e 也可以 e.printStackTrace(),前者是中断程序并抛出异常,后者是打印异常栈,但是不中断后续程序。

在这个程序中最后既可以 throw e 也可以 e.printStackTrace(),前者是中断程序并抛出异常,后者是打印异常栈,但是不中断后续程序。

Topic source
public class Main {

	public static void main(String[] args) {
		try {//追踪这些可能有问题的语句
			System.out.println(tax(2000, 0.1));
			System.out.println(tax(-200, 0.1));
			System.out.println(tax(2000, -0.1));
		} catch (Exception e) {//捕捉上述程序中的异常
			e.printStackTrace();// throw e; 
		}
		
	}

	static double tax(int salary, double rate) {
		// TODO: 如果传入的参数为负,则抛出IllegalArgumentException
		if (salary<0 || rate<0) {
			throw new IllegalArgumentException();//如果遇到负数就抛出该不合法参数异常
		}
		return salary * rate;
	}
}


  • 1

Reply