简体   繁体   English

处理Java异常的初学者

[英]Beginner on handling Java Exceptions

I´m learning java exceptions and have been stuck with questions on one particular example. 我正在学习Java异常,并且一直对一个特定示例有疑问。

Below you see my class ErgaenztesAuto and my main method. 在下面,您可以看到我的类ErgaenztesAuto及其主要方法。 My exeption is catched and working. 我的专家被抓住并开始工作。 Two things I do not understand: 我不明白的两件事:

  1. If I try to access a object outsite the try block, eg ErgaenztesAuto2.meldung() the compiler tells me that he does not find the object ErgaenztesAuto2. 如果我尝试从try块外访问对象,例如ErgaenztesAuto2.meldung(),则编译器会告诉我他找不到对象ErgaenztesAuto2。 If I do the same thing within the try block it works. 如果我在try块中做同样的事情,它会起作用。 Therefore I have to place my whole program within the try block. 因此,我必须将整个程序放在try块中。 What would be the correct approach? 正确的方法是什么? Like only placing the code that I expect to run into an exeption. 就像只放置我希望运行的代码一样。

  2. As soon as my contructor throws an exception the program stops with my custom exception message. 一旦我的构造函数引发异常,程序就会停止,并显示我的自定义异常消息。 The code after the exception is not executed. 异常后的代码未执行。 How can I place the exeption handling that the exception handling within the constructor is taking care of and the rest of the code is still executed. 我该如何放置异常处理程序,该异常处理程序在构造函数中负责处理,其余代码仍在执行。

Thanks! 谢谢! René 雷内

public class ErgaenztesAuto {

// Instanzvariablen
private String besitzer;
private String autotyp;
private String farbe;
private int erstzulassung;
private int leistung;
private int kmStand;
private String standort;
private String fahrgestellnummer;



public ErgaenztesAuto(String besitzer, String autotyp, String farbe,
        int erstzulassung, int leistung, int kmStand, String standort, String fahrgestellnummer)  {
    this.besitzer = besitzer;
    this.autotyp = autotyp;
    this.farbe = farbe;
    this.erstzulassung = erstzulassung;
    this.leistung = leistung;
    this.standort = standort;
    this.fahrgestellnummer = fahrgestellnummer;
    if (kmStand > 0 ) {
        this.kmStand = kmStand;

    } else {
        throw new  IllegalArgumentException("Kein KM Stand kleiner als 0 erlaubt!");
    }

}


public class ErgaenztesAutoTest {

public static void main(String[] args) {

    try
    {
        // Objekt erzeugen
        ErgaenztesAuto ErgaenztesAuto1 = new ErgaenztesAuto("Rene", "BMW", "Rot", 1981, 90, 10, "Berlin", "ABCD");
        ErgaenztesAuto ErgaenztesAuto2 = new ErgaenztesAuto("Rene", "Audi", "Gelb", 2010, 70, -20000, "Muenchen", "WXYZ");
        //ErgaenztesAuto ErgaenztesAuto3 = new ErgaenztesAuto("Rene", "Volkswagen", "Blau", 2017, 65, 1000, "Hamburg", "GHIJ");
        ErgaenztesAuto1.meldung();
        ErgaenztesAuto2.meldung();



    }
    catch (IllegalArgumentException e)    
    {
        System.out.println("Meine Exception trat auf: " + e.getMessage());
    }

When you throw an exception, execution of the try block is cancelled and you go directly to the catch block, then the finally block. 引发异常时,将取消执行try块,然后直接转到catch块,然后再进入finally块。 You can achieve what you want with by only putting the code in a try block that is necessary. 通过仅将代码放在必要的try块中,就可以实现所需的功能。

For example (i made up some class names): 例如(我组成了一些类名):

Car car = null;
try{
    car = new Car(...);
    //do something with car
}catch(Exception e){
    e.printStackTrace();
}
//code here will still be executed and you can access the car object, be sure to check for nullpointer exception though.

Ad 1. 广告1。

Split declaration and initialization: 拆分声明和初始化:

MyObject myObject;
try{
    myObject = new MyObject();
} except (SomeExceptione) {
    e.doSomethingWithException();
}

myObject.performObjectAction();

Ad 2. 广告2。

I am not sure if I understand this part: 我不确定我是否理解这部分内容:

How can I place the exeption handling that the exception handling within the constructor is taking care of and the rest of the code is still executed. 我该如何放置异常处理程序,该异常处理程序在构造函数中负责处理,其余代码仍在执行。

But if you mean to execute something no matter if an exception is thrown you should use finally block. 但是,如果您打算执行某件事,无论是否引发异常,都应该使用finally块。

MyObject myObject;
try{
    myObject = new MyObject();
} except (SomeExceptione) {
    e.doSomethingWithException();
} finally {
    System.out.println("This gets executed always. My Object is: " + myObject.toString());
}

myObject.performObjectAction();

Let me give your some points in my mind just now: 现在让我在脑海中提出您的几点看法:

1) You don't have meldung() method in the class definition ErgaenztesAuto; 1)您在类定义ErgaenztesAuto中没有meldung()方法; as I see it only contains a construction method. 如我所见,它仅包含一种构造方法。 it should goes like : 它应该像这样:

public void meldung() {
    // TODO Auto-generated method stub
    // your own code here
}

2) for the code that you want to continue to run after catching exception, you need to have a FINALLY block: 2)对于要在捕获异常后继续运行的代码,您需要具有FINALLY块:

try {
        // Objekt erzeugen
        ErgaenztesAuto ErgaenztesAuto1 = new ErgaenztesAuto("Rene", "BMW", "Rot", 1981, 90, 10, "Berlin", "ABCD");
        ErgaenztesAuto ErgaenztesAuto2 = new ErgaenztesAuto("Rene", "Audi", "Gelb", 2010, 70, -20000, "Muenchen", "WXYZ");
        ErgaenztesAuto1.meldung();
        ErgaenztesAuto2.meldung();
    } catch (IllegalArgumentException e) {
        System.out.println("Meine Exception trat auf: " + e.getMessage());
    } finally {
        System.out.println("I'M RUNNING AFTER EXCEPTION !!");
        // OTHER CODE LOGIC
    }

3) for the part about object visibility, please read one more java foundation book, that will tell you how to define different objects in different level; 3)关于对象可见性的部分,请再读一本Java基础书籍,它将告诉您如何在不同级别定义不同的对象; so the code goes like: (i tagged them as "line 1-2-3") 因此代码如下:(我将其标记为“ 1-2-3行”)

    // Objekt erzeugen
    ErgaenztesAuto ErgaenztesAuto1 = null; // line 1
    ErgaenztesAuto ErgaenztesAuto2 = null; // line 2
    try {
        ErgaenztesAuto1 = new ErgaenztesAuto("Rene", "BMW", "Rot", 1981, 90, 10, "Berlin", "ABCD");
        ErgaenztesAuto2 = new ErgaenztesAuto("Rene", "Audi", "Gelb", 2010, 70, -20000, "Muenchen", "WXYZ");
        ErgaenztesAuto1.meldung();
        ErgaenztesAuto2.meldung();
    } catch (IllegalArgumentException e) {
        System.out.println(" ErgaenztesAuto1 object is having errors:" + ErgaenztesAuto1); // line 3
        System.out.println("Meine Exception trat auf: " + e.getMessage());
    } finally {
        System.out.println("I'M RUNNING AFTER EXCEPTION !!");
        // OTHER CODE LOGIC
    }

4) one last thing is , in general , you need to follow some JAVA specification, here i take one as "Camel Case naming"; 4)最后一件事是,通常,您需要遵循一些JAVA规范,这里我将其称为“驼峰命名”。 so your objects' name could be changed from 这样您的对象的名称可以从

ErgaenztesAuto ErgaenztesAuto1 ; 
ErgaenztesAuto ErgaenztesAuto2 ; 

to

ErgaenztesAuto ergaenztesAuto1 ; 
ErgaenztesAuto ergaenztesAuto2 ; 

Thanks. 谢谢。

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

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