简体   繁体   English

在Java中引发异常或断言

[英]throwing exception or asserting in java

A very noob question. 一个非常菜鸟的问题。 I am writing a method which does takes in two arrays and then creates a hash map out of it. 我正在写一个方法,该方法接受两个数组,然后从中创建一个哈希映射。 So for example: 因此,例如:

HashMap<String,String> createHash(String[] arr1, String[] arr2){
  //the logic is very simple
   HashMap<String,String> hshmp= new HashMap<String,String>();
   for (int i=0; i < arr1.length;i++){
    hshmp.put(arr1[i],arr2[i]);
  }
  return hshmp
}

Now first thing I want to check is dimensions of both arr1 and arr2..whether they are same or not 现在,我要检查的第一件事是arr1和arr2的尺寸。是否相同

and if not.. then the program quits (gracefully ?? elaborate??) 如果没有,则程序退出(优雅地“精心制作”)

Usually this is assertion??? 通常这是断言??? right?? 对?? but i think assertion in java is optional thingy which you have to enable? 但是我认为Java中的断言是必须启用的可选内容?

Whats a good way to solve this? 解决这个问题的好方法是什么?

The choice between exceptions and assertions depends on some extent to how the method is intended to be used. 异常和断言之间的选择在某种程度上取决于打算使用该方法的方式。

Assertions are intended to verify internal assumptions - if you have control over all calls to createHash and, because of the logic of your code, it should be impossible for the method to be called with different-length inputs, then an assertion might be appropriate. 断言旨在验证内部假设-如果您可以控制对createHash所有调用,并且由于代码的逻辑,因此不可能用不同长度的输入来调用该方法,那么断言可能是合适的。 The thought is, you would enable assertions during development to verify your assumptions, and then disable them in production for performance reasons. 想法是,您将在开发期间启用断言以验证您的假设,然后出于性能原因在生产中禁用它们。

For methods that might accept user input that you have no control over, or be part of a public API, or a library that's used internally by lots of developers, then an exception would be more appropriate, because an exception is guaranteed to be thrown. 对于可能接受您无法控制的用户输入或成为公共API一部分,或被许多开发人员在内部使用的库的方法而言,异常将更合适,因为可以肯定会引发异常。 In public methods, you need to be more proactive about your checking your inputs, and throwing exceptions is typically how that's done. 在公共方法中,您需要更加主动地检查输入,通常会抛出异常。

An IllegalArgumentException is perfect for that purpose: 一个IllegalArgumentException非常适合该目的:

if (arr1.length != arr2.length)
{
    throw new IllegalArgumentException("Arrays do not have the same length: " + 
                                        arr1.length + " != " + arr2.length);
}

I recommend throwing an exception, because this way, the caller of your method can decide what to do when that happens. 我建议抛出一个异常,因为这样,您的方法的调用者可以确定发生这种情况时该怎么做。 The caller can exit the application by putting a System.exit(-1); 调用者可以通过放置System.exit(-1);退出应用程序System.exit(-1); statement or calling your custom terminate procedure (where you save changes, resources, settings, etc) in the catch body for IllegalArgumentException. 语句或在catch主体中为IllegalArgumentException调用自定义终止过程(在其中保存更改,资源,设置等)。

FYI: Yes, assert is a feature you have to enable manually. 仅供参考:是的,assert是您必须手动启用的功能。


Alternatively, you could print out the stacktrace of the error and exit immediately. 或者,您可以打印出错误的堆栈跟踪并立即退出。 But I do not recommend: 但我不建议:

if (arr1.length != arr2.length)
{
    Exception e = new IllegalArgumentException("Arrays do not have the same length: " + arr1.length + " != " + arr2.length);
    e.printStackTrace();
    System.exit(-1);
}

you can do it like this : 你可以这样做:

HashMap<String,String> createHash(String[] arr1, String[] arr2) throws IllegalArgumentException {
  //the logic is very simple
  if(arr1 != null && arr2 !=null && arr1.length == arr2.length){
     HashMap<String,String> hshmp= new HashMap<String,String>();
     for (int i=0; i < arr1.length;i++){
        hshmp.put(arr1[i],arr2[i]);
     }
     return hshmp;
  }
  else
     throw new IllegalArgumentException("Arrays are null or not equally sized");
}

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

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