运行时/已检查/未检查/错误/异常之间的差异

发布于 2024-09-07 18:14:59 字数 99 浏览 7 评论 0原文

什么是运行时异常,什么是检查/未检查异常以及错误/异常之间的区别。为什么有这么多类型?相反,Java 可能只是简单地遵循一个简单的设计(只是尝试/捕获所有类型)来处理程序中的异常情况?

What are the Runtime exceptions and what are Checked/Unchecked Exceptions and difference between Error/Exception.Why these many types? Instead Java may simply follow a simple design(just try/catch all types) to handle an abnormal condition in a program?

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

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

发布评论

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

评论(8

相思碎 2024-09-14 18:14:59

由于我是一个新的Java开发人员,我在区分和处理不同类型的异常时也遇到了一些困难。这就是为什么我对这个主题做了一个简短的记录,每当我感到困惑时,我都会浏览它。这是 Throwable 类层次结构的图像:
Throwable Class Hierarchy

[图片由 JavaTpoint]。

这里需要记住三个关键类:ThrowableExceptionError。其中Exception可以分为两种类型:“Checked Exception”和“Unchecked Exception”。

检查异常:

  • 这些是扩展Throwable的类,除了RuntimeExceptionError之外。
  • 它们也称为编译时异常,因为它们是在编译时检查的,这意味着编译器强制我们要么使用 try/catch 处理它们,要么在函数签名中指出它抛出的异常。 code> 它们并迫使我们在调用者中处理它们。
  • 它们是可通过编程恢复的问题,由代码控制之外的意外情况引起(例如数据库关闭、文件 I/O 错误、错误输入等)。
  • 示例: IOExceptionSQLException

Unchecked Exception:

  • 扩展 RuntimeException 的类> 被称为未经检查的异常。
  • 未经检查的异常不在编译时检查,而是在运行时检查,因此得名。
  • 它们也是通过编程可恢复的问题,但与检查异常不同,它们是由代码流或配置中的错误引起的。
  • 示例: ArithmeticExceptionNullPointerExceptionArrayIndexOutOfBoundsException 等。
  • 由于它们是编程错误,因此可以通过以下方式很好地避免: /明智地编码。例如,“除以零”会产生 ArithmeticException,可以通过对除数进行简单检查来避免。同样,我们可以通过简单地检查引用来避免 NullPointerException:if (object != null) 甚至使用 更好的技术

错误:

  • 错误指的是try/catch未处理的不可恢复的情况。
  • 示例: OutOfMemoryErrorVirtualMachineErrorAssertionError 等。

为什么有这么多类型?

除了 Stephen C 的回答我想说:
异常处理是Java中相对昂贵的操作。 我们不应该将所有异常情况都放在 try/catch 块中。过度使用 try/catch 可能会影响程序性能。

总之,应尽可能以编程方式处理异常。另一方面,我们无法处理错误,因此这些可能是存在多种类型异常的一些逻辑原因。

Since I am a new Java developer, I have also faced some difficulties for distinguishing and dealing with different types of exceptions. That is why I have made a short note on this topic, and whenever I get confused I go through it. Here it is with the image of the Throwable class hierarchy:
Throwable Class Hierarchy

[image courtesy of JavaTpoint].

There are three key classes to remember here: Throwable, Exception and Error. Among these classes Exception can be divided into two types: "Checked Exception" and "Unchecked Exception".

Checked Exception:

  • These are the classes that extend Throwable except RuntimeException and Error.
  • They are also known as compile time exceptions because they are checked at compile time, meaning the compiler forces us to either handle them with try/catch or indicate in the function signature that it throws them and forcing us to deal with them in the caller.
  • They are programmatically recoverable problems which are caused by unexpected conditions outside the control of the code (e.g. database down, file I/O error, wrong input, etc).
  • Example: IOException, SQLException, etc.

Unchecked Exception:

  • The classes that extend RuntimeException are known as unchecked exceptions.
  • Unchecked exceptions are not checked at compile-time, but rather at runtime, hence the name.
  • They are also programmatically recoverable problems but unlike checked exception they are caused by faults in code flow or configuration.
  • Example: ArithmeticException,NullPointerException, ArrayIndexOutOfBoundsException, etc.
  • Since they are programming errors, they can be avoided by nicely/wisely coding. For example "dividing by zero" produces an ArithmeticException, which can be avoided by a simple check on the divisor. Similarly we can avoid NullPointerException by simply checking the references: if (object != null) or even using better techniques.

Error:

  • Error refers to an irrecoverable situation that is not being handled by a try/catch.
  • Example: OutOfMemoryError, VirtualMachineError, AssertionError, etc.

Why are these many types?

In addition to Stephen C's answer I want to say:
exception handling is a relatively expensive operation in Java. We should not put all exceptional situation in a try/catch block. Excessive use of try/catchs may hamper program performance.

In conclusion, Exceptions should be handled programmatically whenever possible. On the other hand, we cannot handle Errors, so these might be some logical reasons why there are many types of exceptions.

风吹短裙飘 2024-09-14 18:14:59

Throwable 位于所有异常的顶部。
在 Throwable 下有 Error 和 Exception。
在 Exception 下面有 RuntimeException。

Java 有两种类型的异常 - 检查异常和非检查异常。检查异常由编译器强制执行(您必须在 throws 子句中声明它们并最终捕获它们)。在 throws 子句中捕获或声明时不强制执行未经检查的异常。

(答案有争议的部分)

Throwable 的存在使得所有异常类型都有一个父类。你永远不应该声明你抛出 Throwable 并且永远不会接住它(除非你真的真的知道你在做什么)。

存在错误表示运行时环境存在问题,程序可能无法从中恢复,例如格式错误的类文件或 VM 内存不足。除非您真的知道自己在做什么,否则您不应该捕获错误。

异常是所有非程序员错误的根源(请参阅 RuntimeException 了解“异常”),例如由于磁盘已满而无法创建文件。你不应该抛出、抛出或捕获异常。如果您必须捕获异常,请确保您知道自己在做什么。

RuntimeException 的存在是为了指示所有程序员错误,例如超出数组末尾或调用空对象上的方法。这些是你应该修复的事情,这样它们就不会抛出异常——这表明你,程序员,搞砸了代码。再次强调,除非你知道自己在做什么,否则你不应该发现这些。

Throwable is at the top off all exceptions.
Underneath Throwable you have Error and Exception.
Underneath Exception you have RuntimeException.

Java has two types of exceptions - checked and unchecked. Checked exceptions are enforced by the compiler (you have to declare them in the throws clause and catch them eventually). Unchecked exceptions are not enforced for catching or declaring in throws clause.

(Controversial part of the answer)

Throwable exists so that there is a parent for all exception types. You should never declare that you throw Throwable and never catch it (unless you really really really know what you are doing).

Error exists to indicate issues with the runtime environment, things that your program probably cannot recover from, such as a badly formatted class file or the VM running out of memory. You should not catch an Error unless you really know what you are doing.

Exception exists as the root for all non-programmer errors (see RuntimeException for the "exception" to this) , such as a file cannot be created because the disk is full. You should not throw, throws, or catch Exception. If you have to catch Exception make sure you know what you are doing.

RuntimeException exists to indicate all programmer error, such as going past the end of an array or calling a method on a null object. These are things that you should fix so that they do not throw exceptions - the indicate that you, the programmer, screwed up the code. Again, you should not catch these unless you know what you are doing.

孤星 2024-09-14 18:14:59

TofuBeer的答案清楚地解释了异常类的含义。

为什么有这么多类型?相反,Java 可能只是遵循简单的设计(只是尝试/捕获所有类型)来处理程序中的异常情况?

为什么?因为它们是必要的!如果没有这 4 个类,按广泛类别处理异常将是不切实际的。

  • 如果没有 Error 类,您将如何捕获“所有致命 JVM 错误”?
  • 如果没有 Exception 类,如何捕获“所有非 JVM 致命错误的异常”?
  • 如果没有 RuntimeException 类,如何捕获“所有未经检查的异常”?

TofuBeer's answer explains clearly what the exception classes mean.

Why these many types? Instead Java may simply follow a simple design(just try/catch all types) to handle an abnormal condition in a program?

Why? Because they are necessary! Without those 4 classes, handling exceptions by broad category would be impractical.

  • How would you catch "all fatal JVM errors" without the Error class?
  • How would you catch "all exceptions that are not JVM fatal errors" without the Exception class?
  • How would you catch "all unchecked exceptions" without the RuntimeException class?
不如归去 2024-09-14 18:14:59
  • 错误(由虚拟机抛出,不应被捕获或处理)
    1. 虚拟机错误
    2. 断言错误
    3. 链接错误...等等
  • 运行时/取消选中异常(编程错误,不应被捕获或处理)
    1. 空指针异常
    2. ArrayIndexOutOfBoundException
    3. IllegalArgumentException ...等等
  • 检查异常(除此之外,应用程序预计会被捕获或处理)
    1. IO异常
    2. FileNotFoundException
    3. SQLException ...等等
  • Error (throws by VM, should not be caught or handled)
    1. VM Error
    2. Assertion Error
    3. Linkage Error ...so on
  • Runtime/Uncheck Exception(programming error, should not be caught or handled)
    1. NullPointerException
    2. ArrayIndexOutOfBoundException
    3. IllegalArgumentException ... so on
  • Check Exception(Anything Else, Applications are expected to be caught or handled)
    1. IOException
    2. FileNotFoundException
    3. SQLException ...so on
是伱的 2024-09-14 18:14:59

检查和非检查异常之间的区别:

检查和非检查异常之间有很多差异,但所有差异都源于一个基本考虑,即异常是否可以由编译器解决。

要记住的要点是:

[1 ] 检查异常意味着编译器检查异常。这意味着编译器强制要求通过 try-catch 块或 throws 关键字来处理此类异常。

[2] 未经检查的异常是编译器不提供任何命令的异常,因为它们可以由开发人员通过编码/编程来解决,因为控制流是可控的,例如 ArithmeticException、NullPointerException ArrayIndexOutOfBoundsException、IllegalArgumentException 、 ETC。

我将其称为“Exception-Identity-Test”,您可以从 java 文档中随机获取任何异常,然后只问它一个问题。 “嘿例外!你能通过编程方式解决吗?”

如果异常显示,那么它是一个未经检查的异常,因为这可以通过代码更改或解决一些计算错误等来解决。

另一方面,如果异常说那么这是检查异常,因为检查异常控制流超出了我们的代码,就像有人更改数据库密码或有人拔掉网络电缆,连接超时(ConnectException),某些资源不是find(FileNotFoundException、ClassNotFound)、SQLException、InvocatonTargetException等,这些是无法通过编程解决的

Difference between Checked and unchecked exceptions:

We have many differences between checked and unchecked exception but all the differences originate from once basic consideration that whether the exception is solvable by compiler or not.

Points to remember are:

[1] Checked exception means Compiler checked Exceptions. It means that compiler mandates that such exception to be handled by try-catch block or throws keyword.

[2] Unchecked exceptions are the ones for which compiler doesn’t provides any mandate as they can be resolved by developer by coding/programing as the control flow is controllable like in ArithmeticException, NullPointerException ArrayIndexOutOfBoundsException, IllegalArgumentException ,etc.

I call it “Exception-Identity-Test” where you take any random exception from java doc and just ask it one question. “Hey Exception! Can you be solved programmatically?”

If the exception says YES then it is an Unchecked Exception as this can be solved by either code change or resolving some calculation mistake etc.

On the other hand if the Exception says No then this is Checked Exception as in checked Exception control flow goes out of our code like if someone changes Database passwords or someone unplugs the network cable ,connection timeout (ConnectException), some resource is not found (FileNotFoundException, ClassNotFound), SQLException, InvocatonTargetException etc. These ones cannot be resolved by programming

七堇年 2024-09-14 18:14:59

这篇文章总结了已检查未检查异常以清晰简洁的方式。

  • 受检查异常受检查异常是可以在编译时检测、识别和检查的异常。如果代码块抛出已检查的异常,则该方法必须处理该异常,或者必须使用 throws 关键字指定该异常。

    • 示例

      public void testDB() 抛出 ClassNotFoundException、SQLException
      {
          Class.forName("com.mysql.jdbc.Driver");
          System.out.println("驱动程序已加载");
          连接 con = DriverManager.getConnection("jdbc:mysql://localhost:3306/selenium","root","root");
          System.out.println("已连接MySQL数据库");
      }
      
    • 我们要么需要使用 throws 指定异常列表,要么需要使用 try-catch{} 块。我在下面的程序中演示了 throws 的用法。

  • 未检查异常未检查异常在编译时不进行检查。 ErrorRuntimeException 类下的 Java 异常是未经检查的异常,并且 throwable 下的所有其他异常均经过检查。

摘要:如果可以合理地预期客户端会从异常中恢复,请将其设置为受检查的异常。如果客户端无法执行任何操作来从异常中恢复,请将其设为未经检查的异常。

This article sumarizes Checked and Unchecked exceptions in a clear and concise way.

  • Checked Exceptions: Checked Exceptions are the exceptions which can be detected, identified and checked at compile time. If a code block throws a checked exception then the method must handle the exception or it must specify the exception using throws keyword.

    • Example:

      public void testDB() throws ClassNotFoundException, SQLException
      {
          Class.forName("com.mysql.jdbc.Driver");
          System.out.println("Driver Loaded");
          Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/selenium","root","root");
          System.out.println("Connected to MySQL DB");
      }
      
    • We either need to specify list of exceptions using throws or we need to use try-catch{} block. I have demonstrated the useage of throws in the below program.

  • Unchecked Exceptions: Unchecked Exceptions are not checked at compiled time. Java exceptions under Error and RuntimeException classes are unchecked exceptions and everything else under throwable is checked.

Summary: If a client can reasonably be expected to recover from an exception, make it a checked exception. If a client cannot do anything to recover from the exception, make it an unchecked exception.

心碎的声音 2024-09-14 18:14:59

运行时异常为您提供了避免捕获、声明异常的灵活性。

Runtime Exceptions provide you with the flexibility to avoid catching, declaring the exceptions.

简单气质女生网名 2024-09-14 18:14:59
Exceptions are two types in java:

1. **Checked Exception: The exceptions which are checked by compiler. 

例如:我们正在对文件执行操作,那么编译器会要求您通过 try-catch 块或 throws 关键字来处理 IOException。

2. Unchecked Exception: The exceptions which are not checked by compiler at run time. 

例如:如果您在没有创建对象的情况下对对象进行操作;在这种情况下,您将得到 NullPointerException。

Exceptions are two types in java:

1. **Checked Exception: The exceptions which are checked by compiler. 

For example: we you are performing operation with file, then compiler will ask you to handle IOException either by try-catch block or throws keyword.

2. Unchecked Exception: The exceptions which are not checked by compiler at run time. 

For example: If you are performing operation on an object without creating it; in this case you'll get NullPointerException.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文