异常处理:抛出、抛出和Throwable

发布于 2024-09-28 06:13:54 字数 102 浏览 5 评论 0原文

你们中的任何人都可以解释一下 throwthrowsThrowable 之间的区别以及何时使用哪一个吗?

Can any of you explain what the differences are between throw, throws and Throwable and when to use which?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(8

左岸枫 2024-10-05 06:13:54
  • 抛出:在编写方法时使用,声明相关方法抛出指定的(已检查的)异常。

    与检查异常相反,运行时异常(NullPointerExceptions 等)可能会在方法声明不抛出 NullPointerException 的情况下抛出。

  • throw:实际抛出异常的指令。 (或者更具体地说,Throwable)。

    throw 关键字后面跟着一个对 Throwable 的引用(通常是异常)。

示例:

在此处输入图像描述


  • Throwable:您可以使用的类必须扩展才能创建您自己的、自定义的、可抛出的。

示例:

在此处输入图像描述


  • throws: Used when writing methods, to declare that the method in question throws the specified (checked) exception.

    As opposed to checked exceptions, runtime exceptions (NullPointerExceptions etc) may be thrown without having the method declare throws NullPointerException.

  • throw: Instruction to actually throw the exception. (Or more specifically, the Throwable).

    The throw keyword is followed by a reference to a Throwable (usually an exception).

Example:

enter image description here


  • Throwable: A class which you must extend in order to create your own, custom, throwable.

Example:

enter image description here


相思碎 2024-10-05 06:13:54
  • throw:抛出对象 t 的语句,其中 t instanceof java.lang.Throwable 必须为 true。
  • throws:方法签名标记,用于指定该方法抛出的已检查异常。
  • java.lang.Throwable:所有可以抛出(和捕获)的对象的父类型。

请参阅此处有关使用异常的教程。

  • throw: statement to throw object t where t instanceof java.lang.Throwable must be true.
  • throws: a method signature token to specify checked exceptions thrown by that method.
  • java.lang.Throwable: the parent type of all objects that can be thrown (and caught).

See here for a tutorial on using exceptions.

九公里浅绿 2024-10-05 06:13:54

这确实很容易理解。

java.lang.Throwable

Throwable 类是
所有错误的超类和
Java 语言中的异常。仅有的
作为 this 实例的对象
类(或其子类之一)是
由 Java 虚拟机抛出或
可以被Java抛出
抛出语句。
同样,只有这个类或其中之一
它的子类可以作为参数
输入 catch 子句。
更多

关键字 throws 用于方法声明中,它指定我们可能从该方法中期望什么样的异常[Throwable class]。

关键字 throw 用于抛出 Throwable 类实例的对象。


请看一些示例:

我们为自己创建一个异常类

public class MyException super Exception {

}

我们创建一个方法,该方法从我们的异常类创建一个对象,并使用关键字 throw 抛出它。

private  void throwMeAException() throws MyException //We inform that this method throws an exception of MyException class
{
  Exception e = new MyException (); //We create an exception 

  if(true) {
    throw e; //We throw an exception 
  } 
}

当我们要使用方法 throwMeAException() 时,我们被迫以特定的方式处理它,因为我们知道它会抛出一些东西,在这种情况下我们有三个选择。

第一个选项是使用块 try 和 catch 来处理异常:

private void catchException() {

   try {
     throwMeAException();
   }
   catch(MyException e) {
     // Here we can serve only those exception that are instance of MyException
   }
}

第二个选项是传递异常

   private void passException() throws MyException {

       throwMeAException(); // we call the method but as we throws same exception we don't need try catch block.

   }

第三个选项是捕获并重新抛出异常

private void catchException() throws Exception  {

   try {
     throwMeAException();
   }
   catch(Exception e) {
      throw e;
   }
}

恢复,当您需要停止某些操作时,您可以抛出异常,该异常将返回到不是某个 try-catch 块的服务器。无论您在何处使用抛出异常的方法,您都应该通过 try-catch 块来处理它或将声明添加到您的方法中。

此规则的例外是 java.lang.RuntimeException,这些异常不必声明。这是关于异常使用方面的另一个故事。

This really easy to understand.

The java.lang.Throwable:

The Throwable class is
the superclass of all errors and
exceptions in the Java language. Only
objects that are instances of this
class (or one of its subclasses) are
thrown by the Java Virtual Machine or
can be thrown by the Java
throw statement.
Similarly, only this class or one of
its subclasses can be the argument
type in a catch clause.
More

The key word throws is used in method declaration, this specify what kind of exception[Throwable class] we may expect from this method.

The key word throw is used to throw an object that is instance of class Throwable.


Lest see some example:

We create ourself an exception class

public class MyException super Exception {

}

The we create a method that create a object from our exception class and throws it using key word throw.

private  void throwMeAException() throws MyException //We inform that this method throws an exception of MyException class
{
  Exception e = new MyException (); //We create an exception 

  if(true) {
    throw e; //We throw an exception 
  } 
}

When we are going to use method throwMeAException(), we are forced to take care of it in specific way because we have the information that it throws something, in this case we have three options.

First option is using block try and catch to handle the exception:

private void catchException() {

   try {
     throwMeAException();
   }
   catch(MyException e) {
     // Here we can serve only those exception that are instance of MyException
   }
}

Second option is to pass the exception

   private void passException() throws MyException {

       throwMeAException(); // we call the method but as we throws same exception we don't need try catch block.

   }

Third options is to catch and re-throw the exception

private void catchException() throws Exception  {

   try {
     throwMeAException();
   }
   catch(Exception e) {
      throw e;
   }
}

Resuming, when You need to stop some action you can throw the Exception that will go back till is not server by some try-catch block. Wherever You use method that throws an exception You should handle it by try-catch block or add the declarations to your methods.

The exception of this rule are java.lang.RuntimeException those don't have to be declared. This is another story as the aspect of exception usage.

请恋爱 2024-10-05 06:13:54

throw - 用于抛出异常。 throw 语句需要一个参数:可抛出的类对象

throws - 用于指定该方法可以抛出异常

Throwable - 这是 Java 语言中所有错误和异常的超类。您只能抛出从 Throwable 类派生的对象。 throwable 包含其线程创建时的执行堆栈的快照

throw - It is used to throw an Exception.The throw statement requires a single argument : a throwable class object

throws - This is used to specifies that the method can throw exception

Throwable - This is the superclass of all errors and exceptions in the Java language. you can throw only objects that derive from the Throwable class. throwable contains a snapshot of the execution stack of its thread at the time it was created

谁的新欢旧爱 2024-10-05 06:13:54

Throw 用于抛出异常,throws(如果我猜对了)用于指示该方法可以抛出特定异常,而 Throwable 类是 Java 中所有错误和异常的超类

如何抛出异常

Throw is used for throwing exception, throws (if I guessed correctly) is used to indicate that method can throw particular exception, and the Throwable class is the superclass of all errors and exceptions in the Java

How to Throw Exceptions

无敌元气妹 2024-10-05 06:13:54

Throw :

用于实际抛出异常,而 throws 是方法的声明性。它们不可互换。

throw new MyException("Exception!);

抛出:

当您在代码中没有使用 try catch 语句但您知道这个特定的类能够抛出某某异常(仅检查异常)时,请使用此选项。在此,您不使用 try catch 块,而是在代码中的适当位置使用 throw 子句编写,并将异常抛出给方法的调用者并由其处理。当函数可能抛出已检查异常时,也会使用 throws 关键字。

public void myMethod(int param) throws MyException 

Throw :

is used to actually throw the exception, whereas throws is declarative for the method. They are not interchangeable.

throw new MyException("Exception!);

Throws:

This is to be used when you are not using the try catch statement in your code but you know that this particular class is capable of throwing so and so exception(only checked exceptions). In this you do not use try catch block but write using the throw clause at appropriate point in your code and the exception is thrown to the caller of the method and is handled by it. Also the throws keyword is used when the function may throw a checked exception.

public void myMethod(int param) throws MyException 
鸵鸟症 2024-10-05 06:13:54

异常有两种主要类型:
运行时异常(未选中):例如。 NullPointerException、ClassCastException、..
检查异常: 例如。 FileNotFoundException、CloneNotSupportedException、..

运行时异常是在运行时发生的异常,开发人员不应尝试捕获或阻止它。您只需编写代码来避免它们或在满足错误条件时发出命令抛出。我们在方法体内使用 throw。

public Rational(int num, int denom){
if(denom <= 0) {
  throw new IllegalArgumentException("Denominator must be positive");
}
this.num=num;
this.denom=denom;
}

然而,对于已检查异常,JVM 希望您处理它,如果不处理,则会给出编译器错误,因此您声明它会抛出该类型的异常,如下所示在clone() 方法中。

Class Employee{
public Employee clone() throws CloneNotSupportedException{
    Employee copy = (Employee)super.clone();
    copy.hireDate = (Date)hireDate.clone();
    return copy;
}
}

There are 2 main types of Exceptions:
Runtime Exceptions(unchecked): eg. NullPointerException, ClassCastException,..
Checked Exceptions: eg. FileNotFoundException, CloneNotSupportedException, ..

Runtime Exceptions are exceptions that occur at runtime and the developer should not try to catch it or stop it. You only write code to avoid them or issue a command throw, when the error criteria is met. We use throw inside the method body.

public Rational(int num, int denom){
if(denom <= 0) {
  throw new IllegalArgumentException("Denominator must be positive");
}
this.num=num;
this.denom=denom;
}

However for Checked Exceptions, the JVM expects you to handle it and will give compiler error if not handled so you declare that it throws that type of exception as seen below in the clone() method.

Class Employee{
public Employee clone() throws CloneNotSupportedException{
    Employee copy = (Employee)super.clone();
    copy.hireDate = (Date)hireDate.clone();
    return copy;
}
}
泼猴你往哪里跑 2024-10-05 06:13:54

与上面相同的答案,但具有复制粘贴的乐趣

public class GsonBuilderHelper {
    // THROWS: method throws the specified (checked) exception
    public static Object registerAndRun(String json) throws Exception {

        // registering of the NaturalDeserializer
        GsonBuilder gsonBuilder = new GsonBuilder();
        gsonBuilder.registerTypeAdapter(Object.class, new NaturalDeserializer());
        Gson gson = gsonBuilder.create();

        Object natural = null;
        try {
            // calling the NaturalDeserializer
            natural = gson.fromJson(json, Object.class);
        } catch (Exception e) {
            // json formatting exception mainly
            Log.d("GsonBuilderHelper", "registerAndRun(json) error: " + e.toString());
            throw new Exception(e);  // <---- THROW: instance of class Throwable. 
        }
        return natural;
    }
}

Same answer as above but with copy-paste pleasure:

public class GsonBuilderHelper {
    // THROWS: method throws the specified (checked) exception
    public static Object registerAndRun(String json) throws Exception {

        // registering of the NaturalDeserializer
        GsonBuilder gsonBuilder = new GsonBuilder();
        gsonBuilder.registerTypeAdapter(Object.class, new NaturalDeserializer());
        Gson gson = gsonBuilder.create();

        Object natural = null;
        try {
            // calling the NaturalDeserializer
            natural = gson.fromJson(json, Object.class);
        } catch (Exception e) {
            // json formatting exception mainly
            Log.d("GsonBuilderHelper", "registerAndRun(json) error: " + e.toString());
            throw new Exception(e);  // <---- THROW: instance of class Throwable. 
        }
        return natural;
    }
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文