Java教程-throw和throws在Java中的区别
throw和throws在Java中的区别
throw和throws是Java中异常处理的概念,其中throw关键字用于从方法或代码块中显式抛出异常,而throws关键字用于在方法的签名中声明异常。
throw和throws关键字之间有许多区别。下面是throw和throws之间的区别列表:
Sr. no. | Basis of Differences | throw | throws |
---|---|---|---|
1. | 定义 | Java throw 关键字用于在代码中、函数内部或代码块中显式抛出异常。 | Java throws 关键字在方法签名中用于声明函数在执行代码时可能抛出的异常。 |
2. | 异常类型 使用 throw 关键字,我们只能传播未经检查的异常,即不能仅使用 throw 传播已检查的异常。 | 使用 throws 关键字,我们可以声明已检查和未检查的异常。但是,throws 关键字只能用于传播已检查的异常。 | |
3. | 语法 | throw 关键字后跟要抛出的 Exception 实例。 | throws 关键字后跟要抛出的异常的类名。 |
4. | 宣言 | 方法中使用了 throw。 | throws 与方法签名一起使用。 |
5. | 内部实施 | 我们一次只能抛出一个异常,即我们不能抛出多个异常。 | 我们可以使用可以由方法抛出的 throws 关键字声明多个异常。例如,main() 抛出 IOException、SQLException。 |
Java throw示例
TestThrow.java
public class TestThrow {
//定义一个方法
public static void checkNum(int num) {
if (num < 1) {
throw new ArithmeticException("\nNumber is negative, cannot calculate square");
}
else {
System.out.println("Square of " + num + " is " + (num*num));
}
}
//主要方法
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 {
//定义方法
public static int divideNum(int m, int n) throws ArithmeticException {
int div = m / n;
return div;
}
//主要方法
public static void main(String[] args) {
TestThrows obj = new TestThrows();
try {
System.out.println(obj.divideNum(45, 0));
}
catch (ArithmeticException e){
System.out.println("\nNumber cannot be divided by 0");
}
System.out.println("Rest of the code..");
}
}
输出:
Java throw和throws示例
TestThrowAndThrows.java
public class TestThrowAndThrows
{
// 定义一个用户定义的方法
// 抛出 ArithmeticException
static void method() throws ArithmeticException
{
System.out.println("Inside the method()");
throw new ArithmeticException("throwing ArithmeticException");
}
//主要方法
public static void main(String args[])
{
try
{
method();
}
catch(ArithmeticException e)
{
System.out.println("caught in main() method");
}
}
}
输出: