Java异常处理

Java程序出现异常时,为了避免程序中断,可以使用try...catch语句捕获异常

package com.jike.exception;
class Exc{
	int a=10;
	int b=10;
}
public class test01 {
	public static void main(String[] args) {
		int tem=0;
		Exc exc=null;
		exc=new Exc();
		try {
			tem=exc.a/exc.b;
			System.out.println(tem);
		}catch (NullPointerException e) {
			System.out.println("空指针异常:"+e);
		}catch (ArithmeticException e) {
			System.out.println("算数异常:"+e);
		}finally {
			System.out.println("程序退出");
		}
		
	}
}

 在定义一个方法的时候可以使用throws关键字声明,使用throws声明的方法不处理异常,将异常传递给方法的调用者处理:

package com.jike.exception;

public class test02 {

	public static void main(String[] args){
		// TODO Auto-generated method stub
		try {
			tell(10,0);
		} catch (Exception e) {
			System.out.println("算术异常:"+e);
		}
	}
	public static void tell(int a,int b)throws ArithmeticException {
		int tem=0;
		tem=a/b;
		System.out.println(tem);
	}

}

 输出:

算术异常:java.lang.ArithmeticException: / by zero

 throw关键字抛出一个异常,抛出的时候直接抛出异常类的实例化对象即可。

package com.jike.exception;

public class test03 {

	public static void main(String[] args) {
		try {
			throw new Exception("实例化异常对象");
		} catch (Exception e) {
			System.out.println(e);
		}
	}
}

 输出:

java.lang.Exception: 实例化异常对象

自定义异常:

package com.jike.exception;
class MyException extends Exception{
	public MyException(String msg) {
		super(msg);
	}
}
public class test04 {

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		try {
			throw new MyException("自定义异常");
		} catch (MyException e) {
			System.out.println(e);
		}
	}
}

 输出:

com.jike.exception.MyException: 自定义异常
原文地址:https://www.cnblogs.com/zhhy236400/p/10436623.html