java异常处理throws throw try-catch实例



java异常处理throws throw try-catch实例。throw用于方法中,我们可以预见的错误。

比如:
if(age<0)
{
Exception e = new Exception();//创建异常对象
throw e;//抛出异常
}
在java代码中如果发生异常的话,jvm会抛出异常对象,导致程序代码中断,这个时候jvm在做的操作就是:创建异常对象,然后抛出。

throws用于方法声明时,多种异常用逗号隔开,用于方法中不可预见的异常。例如:
public void funname()throws IOException,SQLException{

}

此种情况可以用try-catch中:
try
{
fun();
}catch(IOException e)
{
}catch(SQLException e)
{
}
写了三个方法,分别举例说明这三种用法:
public static void fun1(){
int age = -1;
if(age<0){
throw new NumberFormatException();
}
System.out.println(“222222222222″);
}
public static void fun2() throws Exception{
String a = “a”;
Integer.parseInt(a);
System.out.println(“11111111111″);
}

public static void fun3(){
int num = 10;
String str = “a”;
for(int i=0;i<num;i++){
try{
Integer.parseInt(str);
}catch(NumberFormatException e){
try {
throw new NumberFormatException(e.toString());
} catch (Exception e1) {
e1.printStackTrace();
}
}
}
}