简体   繁体   中英

Beginner on handling Java Exceptions

I´m learning java exceptions and have been stuck with questions on one particular example.

Below you see my class ErgaenztesAuto and my main method. 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. If I do the same thing within the try block it works. Therefore I have to place my whole program within the try block. 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. You can achieve what you want with by only putting the code in a try block that is necessary.

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.

Split declaration and initialization:

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

myObject.performObjectAction();

Ad 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.

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; 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:

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; so the code goes like: (i tagged them as "line 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"; so your objects' name could be changed from

ErgaenztesAuto ErgaenztesAuto1 ; 
ErgaenztesAuto ErgaenztesAuto2 ; 

to

ErgaenztesAuto ergaenztesAuto1 ; 
ErgaenztesAuto ergaenztesAuto2 ; 

Thanks.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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