throws与throw

1.throws关键字

在定义一个方法时可以使用thows关键字声明,使用throws声明的方法表示此方法不处理异常,而交给方法的调用处进行处理,throws使用格式如下:

【throws使用格式】

public  返回值类型  方法名称(参数列表...)throws 异常类{}

范例:使用throws关键字

 

class Math{



   public int  div(int i,int j)throws Exception{//方法可以不处理异常

               int  temp=i/j;

               return  temp;

              }



}

  因为出发操作有可能出现异常,也有可能没有异常,所以在上面的代码的div()方法中使用了throws关键字,表示不管是否有异常,在调用此方法处都必须进行异常处理,代码如下:

范例:处理异常

  

package test2;



class Math {

	public int div(int i, int j) throws Exception {

		int temp = i / j;

		return temp;

	}

}



public class ThrowsDemo01 {

	public static void main(String[] args) {

		Math m = new Math();

		try {

			System.out.println("除法操作:" + m.div(60, 90));

		} catch (Exception e) {

			e.printStackTrace();

		}

	}

}

  

package test2;



class Math {

	public int div(int i, int j) throws Exception {

		int temp = i / j;

		return temp;

	}

}



public class ThrowsDemo01 {

	public static void main(String[] args)throws Exception{

		Math m = new Math();

		try {

			System.out.println("除法操作:" + m.div(60, -50));

		} catch (Exception e) {

			e.printStackTrace();

		}

	}

}

  

package test2;



class Math {

	public int div(int i, int j) throws Exception {

		int temp = i / j;

		return temp;

	}

}



public class ThrowsDemo01 {

	public static void main(String[] args){

		Math m = new Math();

		try {

			throw new Exception("自己抛出一个异常");

//			System.out.println("除法操作:" + m.div(60, -50));

		} catch (Exception e) {

			e.printStackTrace();

		}

	}

}

  结果:

java.lang.Exception: 自己抛出一个异常
at test2.ThrowsDemo01.main(ThrowsDemo01.java:14)

throw不会单独使用,一般来讲用户都避免异常的产生,所以不会手工抛出一个异常的。

 

 

你可能感兴趣的:(throws)