使用 try-catch java

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/22644397/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-13 17:02:55  来源:igfitidea点击:

Using try-catch java

javatry-catch

提问by zeesh91

So just got into the basics of try-catch statements in Java and I'm still a bit confused on some differences within the syntax.

所以刚刚进入 Java 中 try-catch 语句的基础知识,我仍然对语法中的一些差异感到有些困惑。

Here is the code I'm trying to analyze and understand. What's the difference between using trythen catch(Exception e)as compared to saying just throwsor throw new?

这是我试图分析和理解的代码。与说 just或相比,使用trythen 有什么区别?catch(Exception e)throwsthrow new

From my understanding, a tryand catchis basically a way to handle the error by outputting a message or passing to another method. However, I think I'm stuck on the syntax aspect of it.

根据我的理解, a tryandcatch基本上是一种通过输出消息或传递给另一个方法来处理错误的方法。但是,我认为我被困在它的语法方面。

Any constructive comments or simple examples clarifying this concept as well as whats going on with the sample code from my book would be appreciated.

任何澄清此概念的建设性评论或简单示例以及我书中的示例代码的内容将不胜感激。

/* Invalid radius class that contains error code */
public class InvalidRadiusException extends Exception {
     private double radius;

/** Construct an exception */
public InvalidRadiusException(double radius) {
       super("Invalid radius " + radius);
       this.radius = radius;
}

/** Return the radius */
public double getRadius() {
    return radius;
 }
}


public class CircleWithException {
/** The radius of the circle */

private double radius;

/** The number of the objects created */
private static int numberOfObjects = 0;

/** Construct a circle with radius 1 */
public CircleWithException() throws InvalidRadiusException {
       this(1.0);
  }

/** Construct a circle with a specified radius */
public CircleWithException(double newRadius) throws InvalidRadiusException {
          setRadius(newRadius);
          numberOfObjects++;
}

/** Return radius */
public double getRadius() {
     return radius;
}

/** Set a new radius */
public void setRadius(double newRadius)
    throws InvalidRadiusException {
if (newRadius >= 0)
  radius =  newRadius;
else
  throw new InvalidRadiusException(newRadius);
}

/** Return numberOfObjects */
public static int getNumberOfObjects() {
      return numberOfObjects;
}

/** Return the area of this circle */
public double findArea() {
    return radius * radius * 3.14159;
 }
}

采纳答案by sinθ

Explanation

解释

From the Java documentation:

Java 文档

[The tryblock] contains one or more legal lines of code that could throwan exception. (The catch and finally blocks are explained in the next two subsections.)

[ try块] 包含一个或多个可能引发异常的合法代码行。(catch 和 finally 块将在接下来的两个小节中解释。)

An exception is a special kind of object. When you write new Exception(), you are creating a new exception object. When you write throw new Exception()you are creating a new error, and then throwing it to the nearest try-catch block, aborting the rest of your code.

一个例外是一种特殊的对象。当您编写时new Exception(),您正在创建一个新的异常对象。当您编写代码时,throw new Exception()您正在创建一个新错误,然后将其抛出到最近的 try-catch 块,从而中止其余代码。

When you throwan exception, it gets caughtby the try-catch block that it's nested in(inside of). That is, assuming the proper catch block for that exception is registered. If the code is not wrapped in a try-catch block, the program with automatically shut down as soon as an error is thrown. Use a try-catch around any code or method that can throw an error, especially because of user input (within reason).

当您抛出异常时,它会它嵌套在(内部)的 try-catch 块捕获。也就是说,假设注册了该异常的正确 catch 块。如果代码未包含在 try-catch 块中,则程序会在抛出错误后立即自动关闭。在任何可能引发错误的代码或方法周围使用 try-catch,尤其是由于用户输入(在合理范围内)。

Some exceptions have to be caught, others are optional to catch. (checked vs. unchecked).

一些异常必须被捕获,其他异常是可选的。(选中与未选中)。

When you add throwsto a method signature, you are announcing to other methods that if they call that method, it has the potential to throw a checkedexception (it is not necessary for unchecked). Notice how it's throwsnot throw. It's not doing an action, it's describing that it sometimes does an action.

当您添加throws到方法签名时,您向其他方法宣布,如果他们调用该方法,则有可能抛出已检查的异常(对于未检查的异常,则不需要)。请注意它throws不是throw. 它不是在做一个动作,而是在描述它有时会做一个动作。

You use this functionality when you don't want to catch the error inside that method, but want to allow the method's that call your method to catch the error themselves.

当您不想捕获该方法中的错误,但希望允许调用您的方法的方法本身捕获错误时,您可以使用此功能。

Exceptions are a way to make your program respond coherently to unexpected or invalid situations and are especially useful when user input is required, though it's also useful in other situations such as File input/output.

异常是一种使您的程序对意外或无效情况做出一致响应的方法,在需要用户输入时特别有用,尽管它在其他情况下也很有用,例如文件输入/输出。

Examples

例子

public CircleWithException() throws InvalidRadiusException {
       this(1.0);
}

Here, the CircleWithException()has the potential to throw an InvalidRadiusException (presumably, the this(1.0) sometimes throws an InvalidRadiusException.)

在这里,CircleWithException()有可能抛出 InvalidRadiusException(大概,this(1.0) 有时会抛出 InvalidRadiusException。)

The code calling this method should have:

调用此方法的代码应具有:

try {
    new CircleWithException(); // This calls the method above
} catch (InvalidRadiusException e) { // The object "e" is the exception object that was thrown.
    // this is where you handle it if an error occurs
}

As I said before, an Exception is just a specific type of object that extends Exception

正如我之前所说,异常只是一种扩展的特定类型的对象Exception

/* Invalid radius class that contains error code */
public class InvalidRadiusException extends Exception {
     private double radius;

/** Construct an exception */
public InvalidRadiusException(double radius) {
       super("Invalid radius " + radius);
       this.radius = radius;
}

/** Return the radius */
public double getRadius() {
    return radius;
 }
}

The above code defines a new type of Exception specific to your program/application. There are many predefined exceptions in the Java Standard Library, but often you need to create your own.

上面的代码定义了一种特定于您的程序/应用程序的新型异常。Java 标准库中有许多预定义的异常,但通常您需要创建自己的异常。

To throw this exception, you first create an InvalidRadiusException object and then throw it:

要抛出这个异常,你首先创建一个 InvalidRadiusException 对象,然后抛出它:

throw new InvalidRadiusException(1.0);

回答by Christian

You can declare a method to throwan exception if you can't(or it's not convinient) to handle the exception inside the method.

如果您不能(或不方便)处理方法内部的异常,您可以声明一个方法来抛出异常。

In your case, you are calling the method setRadiusinside the constructor. If you think that is convinient to handle the exception (that is thrown by setRadius) inside the constructor, you can use a try-catchclause:

在您的情况下,您正在调用setRadius构造函数中的方法。如果您认为setRadius在构造函数中处理异常(由 抛出)很方便,则可以使用try-catch子句:

public CircleWithException(double newRadius) throws InvalidRadiusException {
    try {
        setRadius(newRadius);
        numberOfObjects++;
    } catch (InvalidRadiusException e) {
        setRadius(0); // for example
    }
}

The catchblock contains what you want to do if an exception were thrown. In this case, I'm setting the radius to 0, but you can change this.

catch如果抛出异常,该块包含您想要执行的操作。在这种情况下,我将半径设置为0,但您可以更改它。

Rememberthat it depends in your classes implementation and how you want them to work. If you don't want the constructor to handle this exception, you can throw it (as you are already doing) and handle it in other methods.

请记住,这取决于您的类实现以及您希望它们如何工作。如果您不希望构造函数处理此异常,您可以抛出它(正如您已经在做的那样)并在其他方法中处理它。

回答by rpg711

"throws" is a declaration that a method will throw certain exceptions. This is enforced by the java compiler for checked exceptions, and not for errors or unchecked exceptions.

throws”是一个方法将抛出某些异常的声明。这是由 Java 编译器针对已检查异常强制执行的,而不是针对错误或未检查异常强制执行的。

"throw new" are two keywords in java so we can break it down...

throw new”是Java中的两个关键字,因此我们可以将其分解...

  • "throw" is an operator that throws an exception
  • "new" is an operator that creates a new instance of an object
  • throw”是一个抛出异常的操作符
  • new”是一个创建对象新实例的操作符

the "try" block allows you to execute methods that declare they throw exceptions, and that is where you use the "catch" clause, in order to catch those thrown exceptions.

try”块允许您执行声明它们抛出异常的方法,这就是您使用“catch”子句的地方,以捕获那些抛出的异常。

Additionally there is also the try-with-resourcesblock where you can use a try block to operate on a consumable resource(say, a stream) that implements AutoCloseable, and then close it.

此外,还有try-with-resources块,您可以在其中使用 try 块对实现AutoCloseable的可消耗资源(例如流)进行操作,然后关闭它。

There is also the "finally" clause to a tryblock, which allows you to execute cleanup or any other methods that MUST execute after a tryblock, regardless of whether exceptions occur or not.

try块还有一个“ finally”子句,它允许您执行清理或任何其他必须在try块之后执行的方法,无论是否发生异常。

回答by SamYonnou

There are two types of exceptions

有两种类型的异常

1) Unchecked. These are defined by the Errorand RuntimeExceptionclasses and all of their subclasses. Java does not force you to handle these exception in any way.

1) 未选中。这些由ErrorRuntimeException类及其所有子类定义。Java 不会强制您以任何方式处理这些异常。

2) Checked. These are defined be the Throwableclass and all of its subclasses that do not fall into the category defined in (1). Java forces you to handle these exceptions with a try/catch. If you call a method that can throw such an exception (defined with the throwskeyword) outside of a try block your code will not compile.

2)检查。这些被定义为Throwable不属于 (1) 中定义的类别的类及其所有子类。Java 强制您使用 try/catch 处理这些异常。如果您throws在 try 块之外调用可以抛出此类异常(用关键字定义)的方法,您的代码将无法编译。

throws: This is a way of declaring that a method can potentially throw an exception that must be caught with a try/catch. For example

throws:这是一种声明方法可能抛出异常的方法,该异常必须用 try/catch 捕获。例如

public void doSomething() throws MyException { ... }

is a declaration of a method that can potentially throw an instance of MyException.

是可能抛出 的实例的方法的声明MyException

try/catch/finally: This is a way of handling exceptions that may be produced by some sort of code. The cody you are trying to run goes in the tryblock, the error handling code goes into the catchblock. The optional finallyblock is something that will be executed regardless of whether or not an exception is thrown. In fact the finally block will be called even if you do a returninside your tryor your catch. For example

try/ catch/ finally:这是处理可以由某种代码产生异常的方式。您尝试运行的 cody 在try块中,错误处理代码在catch块中。可选finally块是不管是否抛出异常都会执行的东西。事实上,即使你return在你的try或你的catch. 例如

try {
    doSomething();
} catch (MyException exception) {
    exception.printStackTrace();
}

or an example of using finally:

或使用示例finally

MyResource myResource = getMyResource();
try {
    myResource.open();
    doStuffWithMyResource(myResource);
} catch (Exception exception) {
    exception.printStackTrace();
} finally {
    if (myResource.isOpen()) {
        myResource.close();
    }
}