博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
JAVA高级--异常处理概念和异常处理机制
阅读量:7064 次
发布时间:2019-06-28

本文共 2015 字,大约阅读时间需要 6 分钟。

什么是异常

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

异常分类

    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

你可能感兴趣的文章
gulp配置
查看>>
linux命令截取文件最后n行(所有命令)
查看>>
linux提取指定列字符并打印所有内容(awk)
查看>>
减治算法求n个数中的最小数的位置
查看>>
css3学习 理论之文本
查看>>
Linux 安装python3.7.0
查看>>
<Linux命令行学习 第二节> CentOS - 远程登录管理工具
查看>>
[转]BEHAVOUR TREE2
查看>>
深入理解计算机操作系统(十)
查看>>
XML和Schema命名空间详解
查看>>
npm ERR! Unexpected end of JSON input while parsing near '...inimist":"^1.2.0"}
查看>>
Mybatis Generator逆向工程的使用
查看>>
设计模式(八)_门面模式
查看>>
BFS - 水题
查看>>
软件面试常见题目(转帖)
查看>>
[LeetCode] NO. 387 First Unique Character in a String
查看>>
理解管理信息系统
查看>>
UVA 11991 - Easy Problem from Rujia Liu?
查看>>
CF1101E Polycarp's New Job
查看>>
3d角色模型 制作 全过程 。3d max 。3d role model making process.3d Max
查看>>