Java异常处理

1.异常的概念

1.1什么是异常:Java程序执行发生不正常的情况叫做异常

1.2异常事件分为两种:

错误(error):是指Java虚拟机发生无法解决的严重问题,一般只能通过重写来解决问题

异常(exception): 其它因编程错误或偶然的外在因素导致的一般性问题,异常能够被程序处理,保证程序继续运行下去;例如除数为0、文件没有找到、输入的数字格式不对、网络连接中断、数组下标越界……

1.3异常的种类:运行时异常 和非运行时异常 

数组下标越界(ArrayIndexOutOfBoundsException)

public static void main(String[] args) {
		int[] i = new int[10];
		System.out.println(i[10]);
	}

空指针异常(NullPointerException)

public static void main(String[] args) {
		String aa = new String();
		aa = null;
		System.out.println(aa.toString());
		
	}

数学异常(ArithmeticException)

public static void main(String[] args) {
		int i = 1;
		int j = 0;
		System.out.println(i/j);
	}

类型转换异常(ClassCastException)

public static void main(String[] args) {
		Object d = new Object();
		String string = (String)d;
	}

io异常(IOException ):编译时报错

public static void main(String[] args) {
		FileInputStream f = new FileInputStream(new File("a.txt"));
	}

2.异常的处理

方式一: try catch finally

public static void main(String[] args) {
		int i = 1;
		int j = 0;
		try {
			System.out.println(i/j); // 数学异常,将异常部分给放进try里
		} catch (Exception e) {
			System.out.println("数学异常");//捕获异常后的解决方法
		}finally {
			System.out.println("无论捕没捕获到异常,finally都会执行");
		}
	}

方式二:throws + 异常类型

package O26;

import java.io.File;
import java.io.FileInputStream;

public class lesson1 {
	public static void main(String[] args) {
		Hello h = new Hello();
		try {
			h.hi();//捕获到异常,try catch 解决
		} catch (Exception e) {
			
			e.printStackTrace();
		}
		
	}
	

}

class Hello{
	public void hi() throws Exception{                             //将异常抛出
		FileInputStream f = new FileInputStream(new File("a.txt"));// 产生异常
	}
	
}

3.自定义异常

package O26;

import java.io.File;
import java.io.FileInputStream;

public class lesson1 {
	public static void main(String[] args) {
		Hello h = new Hello();
		try {
			h.hi(0);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

	}

}

//自定义一个异常类,继承exception,定义一些基本方法
class MyException extends Exception {

	public MyException() {
		super();
		// TODO Auto-generated constructor stub
	}

	public MyException(String s) {
		System.out.println("我自己定义的异常");
	}
}

class Hello {
	int i;

	public void hi(int i) throws Exception { // 向上抛出异常
		if (i > 0) {
			this.i = i;
		} else {
			throw new MyException(new String());// 手动抛出异常
		}
	}
}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值