简体   繁体   English

抛出异常而无需在Java中使用try

[英]Throw exceptions without needing to use try in Java

I have this Java code that i want to be able to run. 我有想要运行的Java代码。 It should throw an exception if it have totally been added more than 4 strings, but it should not be needed to use a try/catch the first 4 times the addString method is called. 如果已完全添加了4个以上的字符串,则应引发异常,但是在调用addString方法的前4次中,不需要使用try / catch。

Foo myFoo = new Foo();
myFoo.addString("String A");
myFoo.addString("String B");
myFoo.addString("String C");
myFoo.addString("String D");


boolean exceptionThrown = false;

try {
    myFoo.addString("String E");
} catch (NoRoomForMoreStringsException e) {
    exceptionThrown = true;
}

assertTrue(exceptionThrown);

If i add something like this in the addString function, it will require me to always use a trow/catch statement. 如果我在addString函数中添加这样的内容,它将要求我始终使用trow / catch语句。

public void addString(String str) throws NoRoomForMoreStringsException {
    ...
    if(strings.size() >= 4) {
        throw new NoRoomForMoreStringsException();  
    }

How can i throw an exception in the addString method without needing to always use the try/catch statement? 我如何在addString方法中引发异常而无需始终使用try / catch语句?

Your NoRoomForMoreStringsException can be an unchecked exception . 您的NoRoomForMoreStringsException可以是未经检查的异常 I'm not saying this is a good idea, but it will accomplish what you ask. 我并不是说这是一个好主意,但是它将满足您的要求。

How can i throw an exception in the addString method without needing to always use the try/catch statement ? 如何在不需要始终使用try / catch语句的情况下在addString方法中引发异常?

You need to declare NoRoomForMoreStringsException as RuntimeException as shown below: 您需要将NoRoomForMoreStringsException声明为RuntimeException ,如下所示:

public NoRoomForMoreStringsException extends RuntimeException {

   //methods for custom exception
}

In Java, Exception objects are two types: 在Java中, Exception对象是两种类型:

(1) Checked Exceptions: These exceptions force you to try/catch or declare them in method signature (like your current NoRoomForMoreStringsException). (1)已检查的异常:这些异常迫使您尝试/捕获或在方法签名中声明它们(例如您当前的NoRoomForMoreStringsException)。 The best practice is you need to use these Checked exceptions very carefully ie, only when you have got a recovery action that needs to be done upon catching the exception. 最佳实践是,您需要非常仔细地使用这些Checked异常,即仅当您在捕获异常时需要执行恢复操作时才使用。

(2) Unchecked/Runtime Exceptions : These exceptions don't force you to catch or declare the exception. (2)未检查的/运行时异常:这些异常不会强制您捕获或声明该异常。

Most of the times, you can prefer using Runtime Exceptions (Type 2 above) because in general, we will be able to do very little (like logging) upon getting an exception. 在大多数情况下,您更喜欢使用Runtime Exceptions(上面的Type 2),因为通常,在获得异常后,我们将能够做的很少(例如记录日志)。

Because Checked Exceptions are very noisy (means they force the callers either to catch or declare in method signatures), popular frameworks (like Spring ) try to avoid them ie, Spring throws Runtime Exceptions or even better wraps/converts the Checked Exceptions (if any from JDK) into Runtime Exceptions and then throws. 因为Checked Exceptions非常嘈杂(意味着它们迫使调用者在方法签名中捕获或声明),所以流行的框架(如Spring )会尽量避免它们,即Spring抛出Runtime Exceptions甚至更好地包装/转换Checked Exceptions(如果有)。从JDK)到运行时异常,然后抛出。

So, in short, if you have got a recovery mechanism, you will go for Checked Exception (Type1 above), otherwise, you need to go for RuntimeException (Type2 above) 简而言之,如果您具有恢复机制,则将使用Checked Exception(上面的Type1),否则,就需要使用RuntimeException(上面的Type2)。

You can refer here 你可以在这里参考

The compiler will complain if you do not catch it, but it will still compile and run just fine. 如果您没有抓住它,编译器会抱怨,但是它仍然可以编译并运行良好。

public static void main(String args[]){
  System.out.println("Starting!");
  Foo myFoo = new Foo();
  myFoo.addString("String A");
  myFoo.addString("String B");
  myFoo.addString("String C");
  myFoo.addString("String D");
  myFoo.addString("String E");
}

And the output: 并输出:

Starting!
Adding: String A
Adding: String B
Adding: String C
Adding: String D
Adding: String E
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 4
    at Foo.addString(Foo.java:6)
    at StackOverFlow.main(StackOverFlow.java:9)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM