Java异常处理

1.机制

异常处理机制:抛出异常,捕获异常,如果抛出异常,则必须捕获异常;

异常首先被抛出,然后背捕获,异常被处理后,java程序可继续执行,否则终止运行;


2.捕获异常

2.1 try-catch语句

捕获异常方法:

try{

//监控部分

}catch(Exception e){

//捕获监控部分异常,捕获属于Exception的异常类或者其子类

}

例子:

package com.wugang.demo;

public class ExceptionDemo {
	public static void main(String[] args){
		int i = 0;
		int j = 1;
		try{
			int q = j/i;
		}catch(Exception e){
			System.out.println(e.toString());		
		}
	}
}
运行结果:

java.lang.ArithmeticException: / by zero


从上面例子看出捕获的异常是算数异常,具体原因是除数为0;

2.2 try-catch-finnaly语句

在finnaly语句中,无论是否出现异常,都会执行该部分的语句

例子:

package com.wugang.demo;

public class ExceptionDemo {
	public static void main(String[] args){
		int i = 0;
		int j = 1;
		try{
			int q = j/i;
		}catch(Exception e){
			System.out.println(e.toString());
		}finally{
			System.out.println("finally执行部分");
		}
		
	}
}

运行结果:

java.lang.ArithmeticException: / by zero
finally执行部分

3. 抛出异常

3.1 throws抛出异常

将异常抛给相应的异常类进行处理,多个异常类可用逗号隔开;

例子:

package com.wugang.demo;

public class ExceptionDemo {
	public static void main(String[] args){
		try{
			int i = 9;
			int j = 0;
			divide(i,j);
		}catch(Exception e){
			System.out.println(e.toString());
		}
		
	}

	private static void divide(int i,int j) throws Exception{
		int q = i/j;
	}
}
处理结果:

java.lang.ArithmeticException: / by zero

可以看出divide()方法中抛出了异常,在main()方法中捕获了该异常,当然main()方法中可以继续抛出该异常,但是该异常必须有处理方法


3.2 throw抛出异常

throw总是在放方法中,用此方法来抛出异常,程序回立即停止运行,后面的语句不会执行

例子:

package com.wugang.demo;

public class ExceptionDemo {
	public static void main(String[] args){
		try{
			int i = 0;
			if(i == 0){
				throw new Exception();
			}
			System.out.println("else Exceptiion");
		}catch(Exception e){
			System.out.println(e.toString());
		}
		
	}
}
运行结果:

java.lang.Exception


4. 自定义异常

可以通过继承Exception异常类,重写其异常处理方法,通过关键字throw关键字抛出异常对象,如果在当前方法中处理异常,可以勇try-catch处理,或通过throws将异常抛给调用者,继续下一步处理

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值