Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/360.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 何时选择已检查和未检查的异常_Java_Exception_Checked Exceptions - Fatal编程技术网

Java 何时选择已检查和未检查的异常

Java 何时选择已检查和未检查的异常,java,exception,checked-exceptions,Java,Exception,Checked Exceptions,在Java(或任何其他带有已检查异常的语言)中,当创建自己的异常类时,如何决定是否应检查它 我的直觉是,如果调用方能够以某种有效的方式进行恢复,则会调用选中的异常,而对于无法恢复的情况,则调用未选中的异常会更有效,但我会对其他人的想法感兴趣。来自: 当发生异常时,您必须 捕获并处理异常, 或者告诉编译器您无法处理 通过声明您的方法 抛出该异常,然后返回代码 使用你的方法的人必须 处理该异常(即使它也是如此) 可以选择声明它抛出 异常(如果无法处理它) 编译器将检查我们是否已完成 两件事中的一件(

在Java(或任何其他带有已检查异常的语言)中,当创建自己的异常类时,如何决定是否应检查它

我的直觉是,如果调用方能够以某种有效的方式进行恢复,则会调用选中的异常,而对于无法恢复的情况,则调用未选中的异常会更有效,但我会对其他人的想法感兴趣。

来自:

当发生异常时,您必须 捕获并处理异常, 或者告诉编译器您无法处理 通过声明您的方法 抛出该异常,然后返回代码 使用你的方法的人必须 处理该异常(即使它也是如此) 可以选择声明它抛出 异常(如果无法处理它)

编译器将检查我们是否已完成 两件事中的一件(抓,或 声明)。所以这些被称为Checked 例外情况。但是错误,以及运行时 异常不由检查 编译器(即使您可以选择 捕捉或声明,它不是 必需)。所以,这两个被称为 未检查的异常

错误用于表示这些错误 外部发生的情况 应用程序,例如 系统。运行时异常是 通常发生在 应用程序逻辑。你做不到 在这种情况下什么都可以。什么时候 发生运行时异常时,您必须 重新编写程序代码。那么这些 编译器不会检查这些属性。这些 运行时异常将在 开发、测试阶段。然后 我们必须重构代码以删除 这些错误


我使用的规则是:永远不要使用未检查的异常!(或者当你看不到任何解决办法时)

从使用您的库的开发人员或使用您的库/应用程序的最终用户的角度来看,面对一个由于未经考虑的异常而崩溃的应用程序确实很糟糕。指望一网打尽也不好


这样,最终用户仍然可以看到一条错误消息,而不是应用程序完全消失。

选中的异常对于希望向调用者提供信息(即权限不足、找不到文件等)的可恢复情况非常有用

未经检查的异常很少(如果有的话)用于在运行时通知用户或程序员严重错误或意外情况。如果您正在编写其他人将使用的代码或库,请不要抛出它们,因为他们可能不希望您的软件抛出未经检查的异常,因为编译器不会强制捕获或声明它们


我使用的规则是:永远不要使用未检查的异常!(或者当你看不到任何解决办法时)


相反,有一个非常有力的理由:永远不要使用检查异常。我不愿意在辩论中偏袒任何一方,但似乎有一个广泛的共识,即在事后看来,引入受控例外是一个错误的决定。请不要射击信使,请参考。

这是我的“最后经验法则”。
我使用:

  • 由于调用方(涉及一个)而导致的失败的我的方法代码中的未检查异常
  • 检查异常,查找由于我需要向任何想要使用我的代码的人明确说明的而导致的故障
与前面的答案相比,这是使用一种或另一种(或两者)例外的明确理由(可以同意或不同意)


对于这两个异常,我将为我的应用程序创建我自己的未检查和已检查异常(一个好的实践),除了非常常见的未检查异常(如NullPointerException)

例如,下面这个特定函数的目标是生成(或获取,如果已经存在)一个对象,
意思是:

  • 要生成/获取的对象的容器必须存在(调用者的责任
    =>未检查的异常,并清除此调用函数的javadoc注释)
  • 其他参数不能为空
    (选择编码器将其置于调用方:编码器不会检查null参数,但编码器会记录它)
  • 结果不能为空
    (被呼叫者的责任和代码选择,呼叫者感兴趣的选择
    =>检查异常,因为如果无法创建/找到对象,则每个调用方都必须作出决定,并且必须在编译时强制执行该决定:如果不处理这种可能性,他们就不能使用此函数,这意味着要处理此检查异常)
例如:


/**
*建立一个文件夹
*位于父文件夹下的文件夹(根文件夹或现有文件夹) *@param aFolderName文件夹的名称 *@param aPVob包含文件夹的项目vob(不能为空) *@param aParent包含文件夹的父文件夹 *(不能为空,必须与aPvob位于同一PVOB中) *@param aComment文件夹注释(不得为空) *@返回新文件夹或现有文件夹 *@如果在创建文件夹过程中出现任何问题,则会引发CCException *@如果Apart不在同一PVob中,则抛出断言FailedException *如果aPVob或aParent或aComment为null,则@throws NullPointerException */ 静态公用文件夹makeOrGetFolder(文件夹名称的最终字符串,文件夹名称的最终字符串, 最终IPVob aPVob,最终评论A注释)引发异常{ 文件夹afolders=null; 如果(aPVob.equals(aParent.getPVob()==false){ //未选中的异常,因为调用方无法正常工作 //此功能的记录输入标准 Assert.isLegal(false,“父文件夹必须位于与“+aPVob”)相同的PVob中;} 最后一个字符串ctcmd=“mkfolder”+aComment.getCommentOption()+ “-in”+getPNameFromRepoObject(a
/**
 * Build a folder. <br />
 * Folder located under a Parent Folder (either RootFolder or an existing Folder)
 * @param aFolderName name of folder
 * @param aPVob project vob containing folder (MUST NOT BE NULL)
 * @param aParent parent folder containing folder 
 *        (MUST NOT BE NULL, MUST BE IN THE SAME PVOB than aPvob)
 * @param aComment comment for folder (MUST NOT BE NULL)
 * @return a new folder or an existing one
 * @throws CCException if any problems occurs during folder creation
 * @throws AssertionFailedException if aParent is not in the same PVob
 * @throws NullPointerException if aPVob or aParent or aComment is null
 */
static public Folder makeOrGetFolder(final String aFoldername, final Folder aParent,
    final IPVob aPVob, final Comment aComment) throws CCException {
    Folder aFolderRes = null;
    if (aPVob.equals(aParent.getPVob() == false) { 
       // UNCHECKED EXCEPTION because the caller failed to live up
       // to the documented entry criteria for this function
       Assert.isLegal(false, "parent Folder must be in the same PVob than " + aPVob); }

    final String ctcmd = "mkfolder " + aComment.getCommentOption() + 
        " -in " + getPNameFromRepoObject(aParent) + " " + aPVob.getFullName(aFolderName);

    final Status st = getCleartool().executeCmd(ctcmd);

    if (st.status || StringUtils.strictContains(st.message,"already exists.")) {
        aFolderRes = Folder.getFolder(aFolderName, aPVob);
    }
    else {
        // CHECKED EXCEPTION because the callee failed to respect his contract
        throw new CCException.Error("Unable to make/get folder '" + aFolderName + "'");
    }
    return aFolderRes;
}
/**
 * @params operation - The operation to execute.
 * @throws IllegalArgumentException if the operation is "exit"
 */
 public final void execute( String operation ) {
     if( "exit".equals(operation)){
          throw new IllegalArgumentException("I told you not to...");
     }
     this.operation = operation; 
     .....  
 }
 private void secretCode(){
      // we perform the operation.
      // at this point the opreation was validated already.
      // so we don't worry that operation is "exit"
      .....  
 }
 IllegalArgumentException: I told you not to use "exit" 
 at some.package.AClass.execute(Aclass.java:5)
 at otherPackage.Otherlass.delegateTheWork(OtherClass.java:4569)
 ar ......
 public static MyClass createInstane( Object data1, Object data2 /* etc */ ){ 
      if( data1 == null ){ throw NullPointerException( "data1 cannot be null"); }

  }


  // the rest of the methods don't validate data1 anymore.
  public void method1(){ // don't worry, nothing is null 
      ....
  }
  public void method2(){ // don't worry, nothing is null 
      ....
  }
  public void method3(){ // don't worry, nothing is null 
      ....
  }
x.doSomething(); // the code throws a NullPointerException
if (x==null)
{
    //do something below to make sure when x.doSomething() is executed, it won’t throw a NullPointerException.
    x = new X();
}
x.doSomething();
Socket s = new Socket(“google.com”, 80);
InputStream in = s.getInputStream();
OutputStream out = s.getOutputStream();
String name = null;
... // some logics
System.out.print(name.length()); // name is still null here
String name = ExternalService.getName(); // return null
System.out.print(name.length());    // name is null here