关于Exception的总结

Throwzble包含两个子类,一个是Error,一个是Exception。

Error表示比较严重,而Exception表示是由程序员导致的,是可处理的。

重点说下Exception,总结如下:

1.Exception分为编译时异常和运行时异常(RuntimeException)

通俗的讲,编译时异常就是如果不对异常进行处理,程序在编译时就通不过,会报错。如IOException如果不对其进行处理,在编译时就会报错。看下面代码

class exception 
{
	public static void main(String[] args) 
	{
		
		IOTest();
	}
	
	public static void IOTest()
	{
		FileReader fr=new FileReader("C:\\Users\\Administrator\\Desktop\\abc.txt");
	}
}
编译时是会报错的。

而对于运行时异常,在编译时是可以不对其进行处理的,如下面代码:

class exception 
{
	public static void main(String[] args) 
	{
		System.out.println(test1(4,2));
	}
	public static int test1(int a,int b)
	{
		
	return a/b;
	}
}

上面这些代码是不会报错的,当b=0时编译时也不会报错,运行时才会报错。

2.两种异常的不同处理方式

异常可以被关键字throws和throw处理,两者的区别在于throws用于函数外的声明,用于抛出异常类。而throw用于函数内的抛出,用于抛出异常对象

对于编译时异常(Check),如果函数体内使用throw抛出对象,并且未在函数内使用try进行处理时,必须要在函数上进行声明,否则编译失败。看下面代码:

class exception 
{
	public static void main(String[] args) 
	{
		test2(" ");
	}
	public static void test2(String str)
	{
	if (str==null)
	throw new IOException("故意这样写的");
	
	}
}
上面的代码编译时会报错,因为在throw出编译时异常时没有在函数上进行声明,修改一下如下:

class exception 
{
	public static void main(String[] args) throws IOException
	{
		
		test2(" ");
	}
	
	public static void test2(String str)throws IOException
	{
	if (str==null)
	throw new IOException("故意这样写的");
	
	}
}
编译和运行都没问题,或者修改成下面这样编译运行也没问题,因为有try关键字对其进行了处理。

class exception 
{
	public static void main(String[] args) //throws IOException
	{
		
		test2(" ");
	}
	public static int test1(int a,int b)
	
	public static void test2(String str)//throws IOException
	{
	
		try
		{
			if (str==null)
			throw new IOException("故意这样写的");
		}
		catch (IOException e)
		{
		}
	
	
	}
}
注意若直接调用 throw new IOException("")的函数(没有被try处理),要么try(不需要在调用者外进行声明),要么在调用者外throws,声明异常类。

3.注意异常的三种常见写法

1.try
{
	
}
catch ()
{
}
2.try
{
	
}
catch ()
{
}
finally
{

}
3.try
{
	
}
finally()
{
}
4.异常的处理原则

(1).处理方式有两种,try或throws。

(2).调用到抛出异常的功能时,抛出几个就处理几个,一个try对应多个catch。

(3).多个catch时,父类的放在最下面。

(4).在catch内要进行针对性的处理,不要只是简单的输出。

5.自定义异常类

(1).如果子类异常继承父类异常,子类抛出的异常必须是父类抛出异常的子类或自己。

(2).如果父类没有异常抛出,子类覆盖父类时只能try不能抛。
6.对于特殊关键字finally,里面可以放一定要执行的操作,比如说关闭资源。

finally一定会执行,只有前面遇到System.exit(0)时才不会执行。此外finally和return的执行是有先后顺序的,finally先执行,return后执行,可以由下面的代码来验证。

class exception
{
	public static void main(String[] args)
	{
		System.out.println("执行return--"+test1());
	}
	public static String test1()
	{
		try
		{
			return "return";
		}
		catch (IndexOutOfBoundsException e)
		{
			System.out.println("--");
		}
		finally
		{
			System.out.println("执行finally");
		}
		return null;
	}
}

执行结果为:

执行finally
执行return--return

说明finally先执行,return后执行。













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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值