Java检查异常

问题描述

我正在努力找出有关 Java 中已检查异常的内容。我学到的(我可能是错的)是,如果你抛出一个检查的异常,你有两个选择。

  1. 你必须用 try catch 块来捕捉它
  2. 你用关键字 throws 委托调用

在下面的代码中,我将使用第一个选项,我试图在 Main 类中捕获异常,但我得到“异常 PersonaException 从未在相应的 try 语句的主体中抛出”,好像我从未试着抓住它。我错过了什么?

public class Main{
public static void main(String args[]){
    Persona p = new Persona("Michele","Bianchi");
    Scanner s = new Scanner(system.in);
    System.out.println("Inserisci un numero di telefono: ");
    String tel = s.nextLine();
    
    try{
        p.setTel(tel);
    }
    catch(PersonaException e){
        System.out.println(e.toString());
    }

    System.out.println("Ciao");
    
    System.out.println(p.toString());

}

}

public class Persona{
private String nome;
private String cognome;
private String tel;

public Persona(String nome,String cognome){
    this.nome = nome;
    this.cognome = cognome;
}

public void setTel(String tel){
    if(tel.length()!=10){
        throw new PersonaException("Il numero di telefono è errato");
    }
    else
        this.tel = tel;
    
}

public String getTel(){
    return tel;
}

public String toString(){
    return nome+" "+cognome+": "+tel;
}

}

public class PersonaException extends Exception{
public PersonaException(String msg){
    super(msg);
}

}

解决方法

您缺少的是您编写了无效的 Java 代码。

Java 的链接阶段不关心任何地方的任何方法的内容。故意地。代码今天以一种方式工作;也许明天有人要你稍微改变一下,或者你需要修复一个错误。因此,对您的代码的分析是无关紧要的,它是所有关于签名

因此,在编译时:

try {
   bunchOfStatementsHere();
} catch (CheckedException e) { .. }

javac 查看您在该 try 块中调用的所有事物的所有签名,但查看您所调用的所有事物的代码。在那里调用。

换句话说,如果 bunchOfStatementsHeresetTel("someTel");,java 查看 setTel 方法的签名在代码体!

您的 setTel 方法的签名表明它没有抛出任何东西。它被定义为 public void setTel(String tel) - 那部分是签名,后面 {} 中的所有内容都是正文。

此处没有 throws 子句。

当然,这也意味着您的 Persona.java 文件无法编译 - 您不能 throw new X(); 其中 X 是已检查的异常,除非您捕获它(您没有捕获它),或者把它放在你的 throws 子句中(你没有)。

,

您确实必须声明或处理任何异常,除非它是 RuntimeException。但您也必须在创建异常的地方执行此操作:

public void setTel(String tel) throws PersonaException{
        if(tel.length()!=10){
            throw new PersonaException("Il numero di telefono è errato");
        }
        else
            this.tel = tel;

    }
````

if you dont declare in the signature of setTel,you must handle it here (in a try-catch),which would of course be pointless here.