java语言下异常处理机制总结

1.java中常见的异常有大概四种:

1.1.算数异常 java.lang.ArithmeticException
	int a = 0;
	int b = 10;
	System.out.println(b/a);
1.2.空指针异常 java.lang.NullPointerException
	String a = null;
	a.charAt(3);
1.3.类型转换异常 java.lang.ClassCastException
	Object o = new Integer(1);
	String s = (String)o;
	System.out.println(s);
1.4.数组下标越界 java.lang.ArrayIndexOutOfBoundsException
	String[] s = new String[2];
	System.out.println(s[5]);

2.对异常的处理:

2.1基本语句:

使用 try{
可能会出现异常的代码}
catch(ParseException e){
捕获执行的代码}
finally{
无论是否发生异常都执行的代码}

注意:

没有使用try catch的时候程序出现异常,后续程序不能执行;使用try catch以后,异常被封装在try catch里,后续程序仍能执行。

附上一段代码以便验证

try{
	    int a = 0;
	    int b = 10;
		int c = b/a;
		System.out.println("执行成功");
	}catch(Exception e){
		System.out.println("出现异常");
	}
 		System.out.println("------");
2.2try{}catch{}的机制是一经发现异常就转入catch

代码举例:

//出现异常就转入catch 
try{
		throw new Exception();
	}catch(Exception e){
		System.out.println("xxxx");
	}
2.3多分支异常:

附上代码:

String st = "2019年12-01";
	SimpleDateFormat d = new SimpleDateFormat("yyyy-MM-dd");
try{
	Date dt = d.parse(st);  //解析异常
	
	String s = null;//空指针异常
	s.charAt(1);
	
	int a = 0;
	int b = 10;
	int c = b/a;//算术异常
	
}catch(ParseException e){
	System.out.println("解析异常");
}catch(NullPointerException e1){
	System.out.println("空指针异常");
}catch(ArithmeticException e2){
	 System.out.println("算术异常");
}finally{
	System.out.println("无论如何都会执行");
}

3.关于throw与自定义异常

3.1关于throw的一些看法
Throws的含义是抛出异常自己不处理,谁调用谁处理;不推荐把异常扔给主方法

Cat类:

public class Cat {
public void MiaoWu() throws ParseException{
	Dog a = new Dog();
	a.bit();
}
}

Dog类:

public class Dog {
public void bit() throws ParseException{
	String st = "从那个坏人身上撕了一块肉";
	SimpleDateFormat d = new SimpleDateFormat("yyyy-MM-dd");
	Date dt = d.parse(st); 
	System.out.println("汪汪汪");
}
}

ThrowsTest测试类:

public static void main(String[] args) throws ParseException {
	// TODO Auto-generated method stub
	Dog d = new Dog();
	d.bit();
}

由于在主方法也进行了抛出,故出现了以下错误。
在这里插入图片描述
如果此时改成try{}catch处理异常会如何呢?下面我们来验证

public static void main(String[] args){
	// TODO Auto-generated method stub
	try{
	Dog d = new Dog();
	d.bit();
	}catch(ParseException e){
		System.out.println("出现解析异常");
	}
}

在这里插入图片描述

3.2自定义异常

自定义一个异常:

public class LuckyException extends Exception{
}

Hello类:

public class Hello {
public void hi() throws LuckyException{
	// TODO Auto-generated method stub
	if(Math.random()<0.1)    //百分之九十是异常的,百分之十输出Hello World!
	System.out.println("Hello World!");
	else
	throw new LuckyException();
}
}

Test测试类:

public static void main(String[] args) throws LuckyException {
Hello h = new Hello();
h.hi();
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值