Java中关键字throw和throws的区别

一、系统自动抛异常


当程序语句出现一些逻辑错误、主义错误或类型转换错误时,系统会自动抛出异常:(举个栗子)


public static void main(String[] args) { 
    int a = 5, b =0; 
    System.out.println(5/b); 
    //function(); 
}系统会自动抛出ArithmeticException异常 
或者


public static void main(String[] args) { 
    String s = "abc"; 
    System.out.println(Double.parseDouble(s)); 
    //function(); 
}
系统会自动抛出NumberFormatException异常。




二、throw

throw是语句抛出一个异常,一般是在代码块的内部,当程序出现某种逻辑错误时由程序员主动抛出某种特定类型的异常


public static void main(String[] args) { 
    String s = "abc"; 
    if(s.equals("abc")) { 
      throw new NumberFormatException(); 
    } else { 
      System.out.println(s); 
    } 
    //function(); 
}运行时,系统会抛出异常: 
Exception in thread "main" java.lang.NumberFormatException at......




三、throws

throws是方法可能抛出异常的声明。(用在声明方法时,表示该方法可能要抛出异常)

public void function() throws Exception{......}


当某个方法可能会抛出某种异常时用于throws 声明可能抛出的异常,然后交给上层调用它的方法程序处理


public class testThrows(){
public static void function() throws NumberFormatException{ 
String s = "abc"; 
System.out.println(Double.parseDouble(s)); 

public static void main(String[] args) { 
try { 
function(); 
} catch (NumberFormatException e) { 
System.err.println("非数据类型不能强制类型转换。"); 
//e.printStackTrace(); 
}

猜你喜欢

转载自blog.csdn.net/qzy623569881/article/details/79993279