throws与throw
throws与throw
2)throws表示出现异常的一种可能性,并不一定会发生这些异常;throw则是抛出了异常,执行throw则一定抛出了某种异常;
3)两者都是消极处理异常的方式(这里的消极并不是说这种方式不好),只是抛出或者可能抛出异常,但是不会由函数去处理异常,真正的处理异常由函数的上层调用处理。
throw 就是自己明确的抛出一个异常
throws 是这段代码段有可能出现异常,但自己不做处理,而是交给调用者(caller)去处理,同时throws可以声明多个异常类,这些异常类只是可能触发的,即使触发也由调用方来进行异常处理
如果是Throw,则由自己的方法体来进行处理
class diverse {
public static int div(int x, int y)
throws ArithmeticException,NumberFormatException {
int c = x / y;
return c;
}
}
我写了一个关于这个的代码
package panjun_java;
import java.io.*;
class diverse1 {
public static int dic(int x, int y) {
int c = 1;
try {
c = x / y;
}
catch (Exception ex) {
System.out.print(ex.toString());
}
finally {
return c;
}
}
}
class diverse {
public static int div(int x, int y)
throws ArithmeticException,NumberFormatException {
int c = x / y;
return c;
}
}
public class error {
public error() {
}
public static void main(String[] args) {
int b = diverse1.dic(1, 0);
System.out.print(b);
try{
int a=diverse.div(8,0);
System.out.println(a);
}
catch(ArithmeticException ex)
{
System.out.print("panjun!");
System.out.print(ex.toString());
//输出panjun!java.lang.ArithmeticException: / by zero
}
error error = new error();
try {
//throw new Exception();
}catch(Exception e)
{
System.out.println(e);
}
}
}

浙公网安备 33010602011771号