J8 异常处理

1.catch异常

1.1概念

  • 异常是导致程序中断运行的一种指令流,如果不对异常进行正确处理,则可能导致程序的中断执行,造成不必要的损失

1.2格式

  • 异常格式
try{
    异常语句;
}catch(Exception e){
}finally{
    一定会执行的代码;
}
  • 实例
package com.hanqi.err;

class Exc{
	int i = 10;
}
public class test01 {

	public static void main(String[] args) {
		// TODO 自动生成的方法存根
		int a = 10;
		int b = 0;
		int temp = 0;
		try {
			temp = a / b;
		}catch(Exception e) {
			System.out.println(e);
		}
		System.out.println(temp);
	}
}
//
java.lang.ArithmeticException: / by zero
0

2.java常见异常

2.1多个异常

  • 实例
package com.hanqi.err;

class Exc{
	int a = 10;
	int b = 0;
}
public class test01 {

	public static void main(String[] args) {
		// TODO 自动生成的方法存根
		Exc e = null;
		e = new Exc();
		int temp = 0;
		try {
			temp = e.a / e.b;
			System.out.println(temp);
		}catch(NullPointerException e1) {
			System.out.println("空指针异常"+e1);
		}catch(ArithmeticException e2) {
			System.out.println("算术异常"+e2);
		}finally {
			System.out.println("程序退出");
		}
		
	}
}

2.2常见异常

  • ArrayIndexOutOfBoundsException数组越界异常
  • NumberFormatException数字格式化异常
  • ArithmeticException算术异常
  • NullPointerException空指针异常

3.throws关键字

3.1概念

  • 在定义一个方法的时候可以使用throws关键字声明,使用throws声明的方法表示此方法不处理异常,抛给方法调用者处理
  • 格式
public void tell() throws Exception{}
  • throw关键字抛出一个异常,抛出的时候直接抛出异常类的实例化对象即可,如下
package com.hanqi.err;

public class test03 {

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

	}

}

3.2实例

  • 下列代码中自定义的方法将异常抛给主方法,由主方法进行捕获处理
package com.hanqi.err;

public class test02 {

	public static void main(String[] args) {
		// TODO 自动生成的方法存根
		try {
			tell(10, 0);
		}catch(Exception e) {
			System.out.println("算术异常"+e);
		}
		
	}
	public static void tell(int i, int j) throws ArithmeticException {
		int temp = 0;
		temp = i / j;
		System.out.println(temp);
	}
}
  • 同理,主方法也可以将异常抛给JVM处理
package com.hanqi.err;

public class test02 {

	public static void main(String[] args) throws ArithmeticException {
		// TODO 自动生成的方法存根
		tell(10, 0);
	}
	public static void tell(int i, int j) throws ArithmeticException {
		int temp = 0;
		temp = i / j;
		System.out.println(temp);
	}
}

4.自定义异常

  • 自定义异常直接继承Exception就可以完成自定义异常类
package com.hanqi.err;

class MyException extends Exception{
	public MyException(String msg) {
		super(msg);
	}
}
public class test04 {

	public static void main(String[] args) {
		// TODO 自动生成的方法存根
		try {
			throw new MyException("自定义异常");
		}catch(MyException e) {
			System.out.println(e);
		}
	}
}
posted @ 2021-08-05 23:34  MHDSG  阅读(208)  评论(0)    收藏  举报