栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

【Java异常处理机制理解】

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

【Java异常处理机制理解】

异常处理机制有其二

其一:

try-catch-finally
try{
… //可能产生异常的代码
}
catch( ExceptionName1 e ){
… //当产生ExceptionName1型异常时的处置措施
}
catch( ExceptionName2 e ){
… //当产生ExceptionName2型异常时的处置措施
}[ finally{
… //无论是否发生异常,都无条件执行的语句
} ]
注意:catch中的异常类型如有子父类关系,子类在上,父类在下,否则报错

//举例
public class IndexOutExp {
	public static void main(String[] args) {
		String friends[] = { "lisa", "bily", "kessy" };
		try {
			for (int i = 0; i < 5; i++) {//数组下标越界	
			System.out.println(friends[i]);
		} catch (ArrayIndexOutOfBoundsException e) {
			System.out.println("index error");
		}
		System.out.println("this is the end");
	} 
}

其二:
声明抛出异常

public void readFile(String file) throws FileNotFoundException { ……
//读文件的操作可能产生FileNotFoundException类型的异常
在此对其进行自动抛出
FileInputStream fis = new FileInputStream(file); ……… }

//举例
import java.io.*;
public class ThrowsTest {
	public static void main(String[] args) {
		ThrowsTest t = new ThrowsTest();
		try {
			t.readFile();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	public void readFile() throws IOException {
		FileInputStream in = new FileInputStream("xieruwenjian.txt");
		int b;
	    b = in.read();
		while (b != -1) {
			System.out.print((char) b);
			b = in.read();
		}
		in.close();
	} 
}

而除了已有的异常类以外有时我们还需自己定义一个异常类
定义异常类的要求:
1.继承现有的结构:RuntimeException、Exception
2.提供全局常量SerialVersionUID
3.提供重载的构造器

class MyException extends Exception {
	static final long serialVersionUID = 13465653435L;
	private int idnumber;
	public MyException(String message, int id) {
		super(message);
		this.idnumber = id;
 	}
	public int getId() {
		return idnumber; 
	}	
}

public class MyExpTest {
	public void regist(int num) throws MyException {
		if (num < 0)
			throw new MyException("人数为负值,不合理", 3);
		else
			System.out.println("登记人数" + num);
	}
	public void manager() {
		try {
			regist(100);
		} catch (MyException e) {
			System.out.print("登记失败,出错种类" + e.getId());
		}
		System.out.print("本次登记操作结束");
	}
	public static void main(String args[]) {
		MyExpTest t = new MyExpTest();
		t.manager();
	} 
}

而这生成异常类对象,然后通过throw语句实现抛出操作的行为则被称为手动抛出。

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/855242.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号