java throw关键字



java throw关键字.

声明某方法抛出异常的原因:
包含该方法的类可以被不同的类调用,该方法应告知可能会产生异常
调用该方法的类应该捕获异常

可能产生异常的方法并不确切地知道该如何处理该异常事件
向该方法的调用者抛出异常,异常对象可以从调用栈向后传播,知道有核实的方法捕获它为止
异常传递到main方法后结束,交给JVM处理

在一个方法声明中的throws字句中指明
public int read()throws IOException
{……}
在throws字句中可以同时指明多个异常,之间由逗号隔开
public static void main(String args[])throws IOException,IndexOutOfBoundsException
{……}
例子:
/*
* TextException.java
*
* Created on 2007-11-12, 2:51:35
*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/

package textexception;


/**
*
* @author Administrator
*/
class Text
{
public int devide(int x,int y)throws Exception
{
int result=x/y;
return x/y;
}
}
public class TextException {

/**
* @param args the command line arguments
*/
public static void main(String[] args) {
// TODO code application logic here
//因为在Text类中的devide()方法中抛出了异常,所以必须使用try和catch语句,否则编译无法通过
try
{
int result=new Text().devide(3, 0);
System.out.println(“The result is “+result);
}
catch(Exception e)
{
e.printStackTrace();
}

}

}

http://forgetwuhao.blog.163.com/blog/#m=0&t=1&c=fks_081065083087081069084085074071084080089069085084080