Java中的throw和throws之间的区别
throw和throws都是异常处理的概念,其中throw用于显式地从方法或任何代码块中引发异常,而throw在方法的签名中用于指示此方法可能抛出列出的类型之一例外。
以下是throw和throws之间的重要区别。
掷vs掷示例
JavaTester.java
public class JavaTester{
public void checkAge(int age){
if(age<18)
throw new ArithmeticException("Not Eligible for voting");
else
System.out.println("Eligible for voting");
}
public static void main(String args[]){
JavaTester obj = new JavaTester();
obj.checkAge(13);
System.out.println("End Of Program");
}
}输出结果
Exception in thread "main" java.lang.ArithmeticException: Not Eligible for voting at JavaTester.checkAge(JavaTester.java:4) at JavaTester.main(JavaTester.java:10)
示例
JavaTester.java
public class JavaTester{
public int division(int a, int b) throws ArithmeticException{
int t = a/b;
return t;
}
public static void main(String args[]){
JavaTester obj = new JavaTester();
try{
System.out.println(obj.division(15,0));
}
catch(ArithmeticException e){
System.out.println("You shouldn't divide number by zero");
}
}
}输出结果
You shouldn't divide number by zero