一、throw、throws详解
抛出一个异常
用法:Way1:throwsnew Exception();//常写为一个语句,抛出一个异常
Way2:Exceptione=new Exception();//像使用类和对象一样,创建一个异常
throw e; //再它抛出
异常的抛出:有两种方式:系统自己抛出 或 用throw抛出
异常抛出后,后面的语句都不执行了 它直接去找catch或者 throws
它是一种对异常的声明,常写再函数后面,表示这个函数可能会出现某些异常;
格式如下 :
Voidf2( ) throws Exception
{
inta=4/0; //系统自动抛出异常
}
Exception是所有异常的父类,如果将它写在catch里面,可以捕获任何类型的异常,因为子类可以赋给父类。
void f1( )throws Exception
{
inta=4/2; //没有异常
}
void f3( )throws Exception
{
thrownew Exception();
//用throw语句抛出异常
}
也可以自己写一个类继承Exception 如calssmyException extends Exception
throws的作用:
它的作用就是(机器比喻),一旦它看到这个函数出现了异常,它立刻将这个异常抛给给调用这个函数的上一级函数(相当于上报),让上一级函数去处理它。
如果是主函数调用的f函数,那么上一级函数就是主函数;
如果是其他函数调用的f函数,那么上一级就是其他函数。
上一级函数处理:要么捕获它,要么抛出它(如果是检查性异常,需要用throw抛出;非检查性异常自动抛出)
二、检查性异常和非检查性异常
public class t1{
public static void main()
{
A a=new A();
try{
a.B();
}
catch(Exception e)
{
System.out.println("hello!");
}
}
}
class A{
void B()
{
C();
}
void C()
{
D();
}
void D()
{
paochu();
}
void paochu()
{
throw new IllegalArgumentException();//非检查性异常
}
}
import java.io.IOException;
public class t2 {
public static void main(String[]args)throws Exception
{
try{
P a=new P();
a.A();
}
catch ( IOException e)
{
System.out.println("Catch!");
}
}
}
class P{
void A() throws IOException
{
B();
}
void B() throws IOException
{
C();
}
void C() throws IOException
{
D();
}
void D() throws IOException
{
setRadius();
}
void setRadius() throws IOException {
throw new IOException();
}
}
既在同一个函数里面,抛出一个异常,既在函数中声明了throws 又用try去处理了它,会出现怎么样的情况?
public class t3 {
public static void main(String[]args)
{
try{
f();
}
catch(Exception e)
{
System.out.println("catch in main");
}
}
public static void f() throws Exception
{
try
{
throw new Exception();
}
catch(Exception e)
{
System.out.println("catch in f");
}
}
}
测试结果:catch优先于 throws
三、finally
public class t4 {
public static void main(String[]args)
{
f1();
// f2();
}
public static void f1()
{
try
{
throw new Exception();
}
catch(Exception e)
{ System.out.println("f cacth");
return;
}
finally
{
System.out.println("I'm in finally");
}
}
public static void f2() throws Exception
{
try
{
throw new Exception();
}
catch(Exception e)
{ System.out.println("f cacth");
throw new Exception();
}
finally
{
System.out.println("I'm in finally");
}
}
}
四、练习
下列程序输出结果是?
public class t5 {
public static void main(String[]args)
{
int i=0;
try
{
for(i=0;i<10;i++)
{
try
{
if(i%3==0)
throw new Exception();
System.out.println("1:"+i+",");
}
catch(Exception e2)
{
System.out.print("2:"+i+",");
i+=2;
if(i%3==2)
throw new Exception();
return;
}
finally
{
i*=2;
System.out.print("3:"+i+",");
}
}
}
catch(Exception e2)
{
System.out.print("4:"+i+",");
return;
}
finally
{
System.out.print("5:"+i);
}
}
}
答案是:2:0,3:4,4:4,5:4