JAVA高级--异常处理概念和异常处理机制

什么是异常

  程序运行的过程中发生的一些不正常事件

异常分类

    Throwable

      Error  错误  

      Exception  

        IOException          

        RuntimeException    编程错误    可以不用采用异常处理

java的异常通过两种机制来处理

捕获  try-catch-finally

    try 监控   catch  处理   finally  总是执行

package com.date;

import java.util.InputMismatchException;
import java.util.Scanner;

public class TryDemo {
  public static void main(String[] args) {
	System.out.println("请输入一个数字");
	Scanner input=new Scanner(System.in);
	int a=input.nextInt();
	int res=0;
	try {
		 res=10/a;
	}catch (Exception e) {
		System.out.println(e.getMessage());
	}finally {//释放资源,比如关闭打开的文件
		System.out.println("结果为:"+res);
	}	
	/*} catch (InputMismatchException e) {
		System.out.println(e.getMessage());
		e.printStackTrace();
	}catch (ArithmeticException e) {
		System.out.println();
	}*/
	
	
}
}

  

抛出 throw,throws

    throw   手动抛出异常(弹出)

    throws  声明方法抛出异常

 

package com.date;

public class throwDemo {
   public static void main(String[] args) {
	   Bar bar=new Bar();
	  try {
		  bar.enter(15);
	} catch (IllegalArgumentException e) {
		System.out.println(e.getMessage());
	}
	 System.out.println("end");  
}
}

class Bar{
	public void enter(int age) throws IllegalArgumentException {
		if(age<19) {
			throw new IllegalArgumentException("年龄不合格");
		}else {
			System.out.println("欢迎");
		}
	}
}

  

自定义异常

必须从已有的异常类继承    

 Exception   必须用throws
package com.date;

public class zidingyiyichDemo {
   public static void main(String[] args) {
	   Bar1 bar=new Bar1();
		  try {
			  bar.enter(18);
		} catch (AgeLessThanEighteenException e) {
			System.out.println(e.getMessage());
		}
		 System.out.println("end"); 
}
}

class AgeLessThanEighteenException extends Exception{
	private String message;//描述异常信息

	public AgeLessThanEighteenException(String message) {
		this.message = message;
	}
	
	@Override
	public String getMessage() {
		return message;
	}
}

class Bar1{
	public void enter(int age) throws AgeLessThanEighteenException {
		if(age<19) {
			throw new AgeLessThanEighteenException("年龄不合格");
		}else {
			System.out.println("欢迎");
		}
	}
}

  

 

转载于:https://www.cnblogs.com/tanlei-sxs/p/9955761.html

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值