在java中使用assert的是什么 [英] what is the use of assert in java

查看:676
本文介绍了在java中使用assert的是什么的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述


可能重复:

assert做什么?


断言测试程序员的假设在开发过程中没有为异常写异常处理程序这是我得到的,当我在搜索 assert 时。



除此之外,人们还表示,它是异常处理的替代方法。当您不想花时间编写异常处理代码时,断言将进入图片。但是,我没有得到工作和使用。任何人解释这个例子。

  class AssertExample {

public static void main(String [] args){
int x = 0;
assert(x> 0)? 断言失败:断言通过;
System.out.println(finished);
}}


解决方案

assert 不是一种方式来处理异常,它是一种检测的方式。 (因此,你发现的描述看起来有点不符合我的说法)。这基本上是一种说法:


是真实的。如果没有,请抛出错误。


你如何处理这个错误是完全不同的。您可以在检测到它的函数中处理它,您可能会在调用它的函数中处理它,您可以在应用程序级别的堆栈顶部处理它。


请记住,捕获异常(这是正在使用的编程语言的结构)和有意义地处理异常之间有明显的区别(这是一种独立于所使用语言的逻辑构造)。只有抓住例外,你才能真正地做某事。否则,让它们将堆栈起泡到可以对其做某事的其他代码。 (但是由于 assert 没有捕获错误,它会抛出它们,它应该被准确地用在你试图使用它的地方...错误的点

c $ c> assert ,看起来你很亲密。这不是真正的正确用法:

  assert(x> 0)? 断言失败:断言通过; 

您正在处理 assert 它只是一个布尔值。然后,使用? :运算符,你正在关闭该布尔值...好吧,没有真正做任何事情。只需返回一行字符串(断言失败断言传递)到一行代码关闭,但不完全。



assert 本身正在做的不仅仅是检查条件。它通过抛出错误或允许代码路径继续来响应该条件。它使用运算符,但不是的一部分? :运算符。所以我想你想要做的是这样的:

  assert(x> 0):assertion failed 

这基本上是说:


x应该总是大于0.如果不是,一些是非常错误的。停止做任何事情并引发错误。


这将引发一个 AssertionError with消息断言失败(其中,您自然希望用更有意义和有用的消息替换,包括有关正在检查的值的有用的运行时信息以帮助您的调试)。



然后,在其他地方,您将处理该 AssertionError 并以某种方式对其进行响应。



使用 assert 非常类似于这样的东西,只有更短和更有表现力的意图:

  if(x <= 0)抛出新的CustomException(assertion failed); 

如您所见, assert 只需一点点清洁:




  • 使用特定的关键字来提醒您注意以下事实:检查条件是为了唯一目的验证一个假设如果可能会这样做,或者由于任何其他原因可能会解除新的代码路径。

  • 抛出特定的错误可以将其从其他错误中除去。注意我使用 CustomException 来做同样的事情,但是 AssertionError 是更常见的/预期的。 >
  • 使用较少的代码。

  • 演示真实条件,而不是反向或虚假条件。在大多数情况下,真实情况更容易阅读,并更清楚地表达了代码的意图。

  • 遵循惯例,更为惯用。

  • 将代码与代码的其余部分分开,用于特定目的,向其他开发人员指示断言应仅断言。 (所以其他开发人员不应该将其修改为第二个代码路径,可能会为断言添加副作用。)

  • 对于正在运行的应用程序,可以非常轻松地打开或关闭全局。 Java允许您在任何给定的运行时环境中启用或禁用对断言的检查。这对于全球管理断言而言十分方便。作为一个跨部门的关注。


Possible Duplicate:
What does assert do?

assert tests the programmer's assumption during development without writing exception handlers for an exception This is what i got, when i was searching about the assert.

Apart from this, people also said, it is alternative of exception handling. Assertion will come into the picture when you don't want to take the time to write the exception handling code. But, i didn't get the working and uses. Anyone explain this example.

class AssertExample {

    public static void main(String[] args) {
        int x = 0;
        assert (x > 0) ? "assertion failed" : "assertion passed";
        System.out.println("finished");
    } }

解决方案

assert isn't a way to handle exceptions, it's a way to detect them. (Thus, the descriptions you're finding seem a little off the mark to me.) It's basically a way to say:

This should be true. If it isn't, throw an error.

How you handle that error is an entirely different concern. You might handle it right there in the function that detected it, you might handle it in the function that called it, you might handle it at the very top of the stack at the application level, etc.

Keep in mind that there's a significant difference between catching an exception (which is a construct of the programming language being used) and meaningfully handling an exception (which is a logical construct independent of the language being used). Only catch exceptions where you can actually do something about them. Otherwise, let them bubble up the stack to other code that can do something about them. (But since assert doesn't catch errors, it throws them, it should be used exactly where you're trying to use it... the point at which an error can be detected, even if it can't be handled.)

Looking at your attempt to use assert, it looks like you're close. This isn't really the correct usage:

assert (x > 0) ? "assertion failed" : "assertion passed";

You're treating the assert as though it's just a boolean. And then, using the ? : operator, you're keying off of that boolean to... well... not really do anything. Just return a string ("assertion failed" or "assertion passed") to a line of code that doesn't do anything with that string.

Close, but not quite.

The assert itself is doing more than just checking a condition. It's responding to the condition by either throwing an error or allowing the code path to continue. It uses an : operator, but not as part of the ? : operator. So I think what you're trying to do is this:

assert (x > 0) : "assertion failed";

This is basically saying:

x should always be greater than 0. If it isn't, something is very wrong. Stop doing anything and raise an error.

This will raise an AssertionError with the message "assertion failed" (which, naturally, you'd want to replace with a more meaningful and useful message, including any helpful runtime information about the values being examined to help with your debugging).

Then, elsewhere, you would handle that AssertionError and respond to it in some way.

Using the assert is very similar to something like this, only shorter and a little more expressive to its intent:

if (x <= 0) throw new CustomException("assertion failed");

As you can see, the assert is just a little cleaner in that it:

  • Uses a specific keyword to call attention to the fact that it's checking a condition for the sole purpose of validating an assumption. An if might be doing that, or it might be forking off a new code path for any other reason.
  • Throws a specific error which can be filtered apart from other errors. Note my use of a CustomException to do the same thing, but AssertionError is more commonly known/expected.
  • Uses less code.
  • Demonstrates the true condition, as opposed to the inverse or false condition. In the majority of cases, the true condition is easier to read and more clearly expresses what the code intends.
  • Follows convention and is more idiomatic.
  • Sets the code apart from the rest of the code as being for a specific purpose, indicating to other developers that the assertion should be only an assertion. (So other developers shouldn't modify it as a second code path, possibly adding side-effects to the assertion.)
  • Can be very easily turned on or off globally for the running application. Java allows you to enable or disable the checking of assertions during any given runtime context. This is very handy for globally managing assertions as a cross-cutting concern.

这篇关于在java中使用assert的是什么的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆