ArrayList 如何从构造函数中的一项捕获异常

ArrayList how catch exception on one item from constructor

如何从数组列表中捕获一项并抛出异常? 我尝试编译这个程序,但它是一个错误。 这是 film.add 行的消息内容:rok 无法解析为变量。

这是我的代码。 请快速回答并感谢

我有两个class。 class 电影和另一个 class

 public class Film {

String tytul;
int rok;
double ocena;
String imierezysera;
String nazwiskorezysera;

public String toString()
{
    return tytul+" "+rok+" "+ocena+" "+imierezysera+" "+nazwiskorezysera;
}


public String gettytul() {
    return tytul;
}
public void settytul(String tytul) {
    this.tytul = tytul;
}
public int getrok() {
    return rok;
}
public void setrok(int rok) {
    this.rok = rok;
}
public double getocena() {

    return ocena;

}
public void setocena(double ocena) {
    this.ocena = ocena;
}
public String getimierezysera() {
    return imierezysera;
}
public void setimierezysera(String imierezysera) {
    this.imierezysera = imierezysera;
}
public String getnazwiskorezysera() {
    return nazwiskorezysera;
}
public void setnazwiskorezysera(String nzawiskorezysera) {
    this.nazwiskorezysera = nzawiskorezysera;
}

public Film(String tytul, int rok, double ocena, String imierezysera, String nazwiskorezysera) {

   this.tytul= tytul;

   this.rok= rok;
    this.ocena= ocena;
    this.imierezysera= imierezysera;
    this.nazwiskorezysera= nazwiskorezysera;
}



public String wyswietl() {
    // TODO Auto-generated method stub
    return tytul+" "+rok+" "+ocena+" "+imierezysera+" "+nazwiskorezysera;
}



}

}

另一个class

ArrayList<Film> film = new ArrayList<>();
System.out.println("title");
        String tytul;
        tytul = sc.next();
    try{
        System.out.println("year");
        int rok;
        rok = sc.nextInt();
        }catch(Exception e)
        {System.out.println("Wrong value");}



        System.out.println("rating");
        double ocena;
        ocena =sc.nextDouble();

        System.out.println("name");
        String imierezysera;
        imierezysera = sc.next();

        System.out.println("surename);
        String nazwiskorezysera;
        nazwiskorezysera = sc.next();
        film.add(new Film(tytul,rok,ocena,imierezysera,nazwiskorezysera));

这是我的代码

rok 已定义且仅存在于 try/catch 块的范围内。

注意:如果 nextInt() 失败,它不会消耗单词,您的 rating 可能是无效的 year

你可以这样写

String yearStr = sc.next(); // always read the word, even if invalid
int rok = Integer.MIN_VALUE; // value to use if year is invalid.
try {
    rok = Integer.parseInt(yearStr);
} catch (InvalidArgumentException e) {
    System.out.println("Ignoring invalid year " + yearStr);
}

捕获异常然后忽略它而不检查发生了什么错误通常不是一个好主意。除非您知道每个可能的异常,否则您可能会得到意想不到的异常。