使用throw和throws实现异常处理

使用throws声明异常类型


 

  • 可以通过 throws 声明将要抛出何种类型的异常,通过 throw 将产生的异常抛出
  • 如果一个方法可能会出现异常,但没有能力处理这种异常,可以在方法声明处用 throws 子句来声明抛出异常
  • throws 语句用在方法定义时声明该方法要抛出的异常类型
    • public void method() throws Exception1, Exception2, ..., ExceptionN{//可能产生异常的代码}
  • 当方法抛出异常列表中的异常时,方法将不对这些类型及其子类类型的异常作处理,而抛向调用该方法的方法,由他去处理
  • 例:
public class TryDemoThree {

	public static void main(String[] args) {
		/*try {
			int result = test();
			System.out.println("one和two的商是:" + result);
		} catch (ArithmeticException e) {
			System.out.println("除数不允许为零");
			e.printStackTrace();
		}catch(InputMismatchException e){
			System.out.println("请输入整数");
			e.printStackTrace();
		}*/
		try{
			int result = test();
			System.out.println("one和two的商是:" + result);
		}catch(ArithmeticException e){
			
		}catch(InputMismatchException e){
			
		}catch(Exception e){
			
		}
		int result2=test();
	}

	/*通过throws抛出异常时,针对可能出现的多种异常情况,解决方案:
	 * 1、throws后面接多个异常类型,中间用逗号分隔
	 * 2、throws后面接Exception
	 * */
	/**
	 * 测试接收数据相除结果的方法
	 * @return 两个接收数据的商
	 * @throws ArithmeticException
	 * @throws InputMismatchException
	 */
	public static int test() throws ArithmeticException,InputMismatchException{
		Scanner input = new Scanner(System.in);
		System.out.println("=====运算开始=====");
		System.out.print("请输入第一个整数:");
		int one = input.nextInt();
		System.out.print("请输入第二个整数:");
		int two = input.nextInt();
		System.out.println("=====运算结束=====");
		return one / two;
	}

	/*public static int test() throws Exception{
		Scanner input = new Scanner(System.in);
		System.out.println("=====运算开始=====");
		System.out.print("请输入第一个整数:");
		int one = input.nextInt();
		System.out.print("请输入第二个整数:");
		int two = input.nextInt();
		System.out.println("=====运算结束=====");
		return one / two;
	}*/

}

 
 

使用throw抛出异常对象


 

  • throw 用来抛出一个异常,规避可能出现的风险,完成一些程序的逻辑
  • 例如:throw new IOException();
  • throw 抛出的只能够是可抛出类 Throwable 或者其子类的实例对
  • 例:
public class TryDemoFour {

	public static void main(String[] args) {
	/*
	 * throw抛出异常对象的处理方案:
	 * 1、通过try..catch包含throw语句--自己抛自己处理
	 * 2、通过throws在方法声明出抛出异常类型--谁调用谁处理--调用者可以自己处理,也可以继续上抛
	 *    此时可以抛出与throw对象相同的类型或者其父类
	 */
	// 描述酒店的入住规则:限定年龄,18岁以下,80岁以上的住客必须由亲友陪同
	public static void testAge() {
	
		try {
			System.out.println("请输入年龄:");
			Scanner input = new Scanner(System.in);
			int age = input.nextInt();
			if (age < 18 || age > 80) {
				throw new Exception("18岁以下,80岁以上的住客必须由亲友陪同");
			} else {
				System.out.println("欢迎入住本酒店");
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}

 
 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值