throw 和 throws 是在Java中是异常处理的概念,其中 throw 关键字从方法或代码块中显式抛出异常,而 throws 关键字用于方法的签名。
throw 和 throws 有很多区别, 下面列出了 throw 和 throws 的区别:
对比项 | throw | throws |
---|---|---|
定义 | Java throw关键字用于在代码中、函数内部或代码块中显式地抛出异常。 | Java throws 关键字用于方法签名中,用于声明函数在执行代码时可能抛出的异常。 |
异常类型 | 使用 throw 关键字,只能传播未检查的异常,即不能仅使用 throw 传播已检查的异常。 | 使用 throws 关键字,可以声明已检查和未检查的异常。但是 throws 关键字只能用于传播已检查的异常。 |
语法 | throw 关键字后跟要抛出的异常实例。 | throws 关键字后跟要抛出的异常的类名。 |
声明 | throw 在方法内使用。 | throws 与方法签名一起使用。 |
内部实现 | 一次只能抛出一个异常,即我们不能抛出多个异常。 | 使用可以由方法抛出的 throws 关键字声明多个异常。例如,main() 抛出 IOException 、SQLException 。 |
Java throw示例
代码文件:TestThrow.java
public class TestThrow {
//defining a method
public static void checkNum(int num) {
if (num < 1) {
throw new ArithmeticException("\ n Number is negative, cannot calculate square");
}
else {
System.out.println("Square of " + num + " is " + (num*num));
}
}
//main method
public static void main(String[] args) {
TestThrow obj = new TestThrow();
obj.checkNum(-3);
System.out.println("Rest of the code..");
}
}
执行上面示例代码得到以下结果 -
Java throws示例
代码文件:TestThrows.java
public class TestThrows {
//defining a method
public static int divideNum(int m, int n) throws ArithmeticException {
int div = m/n;
return div;
}
//main method
public static void main(String[] args) {
TestThrows obj = new TestThrows();
try {
System.out.println(obj.divideNum(45, 0));
}
catch (ArithmeticException e){
System.out.println("
Number cannot be divided by 0");
}
System.out.println("Rest of the code..");
}
}
执行上面示例代码得到以下结果 -
Java throw和throws示例
示例代码文件:TestThrowAndThrows.java
public class TestThrowAndThrows
{
// defining a user-defined method
// which throws ArithmeticException
static void method() throws ArithmeticException
{
System.out.println("Inside the method()");
throw new ArithmeticException("throwing ArithmeticException");
}
//main method
public static void main(String args[])
{
try
{
method();
}
catch(ArithmeticException e)
{
System.out.println("caught in main() method");
}
}
}
执行上面示例代码,得到以下结果 -
欢迎任何形式的转载,但请务必注明出处,尊重他人劳动成果。
转载请注明:文章转载自 有区别网 [http://www.vsdiffer.com]
本文标题:Java中throw和throws的区别
本文链接:https://www.vsdiffer.com/vs/difference-between-throw-vs-throws-in-java.html
免责声明:以上内容仅是站长个人看法、理解、学习笔记、总结和研究收藏。不保证其正确性,因使用而带来的风险与本站无关!如本网站内容冒犯了您的权益,请联系站长,邮箱: ,我们核实并会尽快处理。