Java – handling new exceptions in anonymous inner classes

I have the following situations:

/** Get a list of records */
public ArrayList<Record> foo() throws BazException{

    // Create the list
    static ArrayList<Record> records = new ArrayList<Record>();

    // Use MyLibrary to load a list of records from the file
    String str = SomeoneElsesLibrary.loadData(new File("mydata.dat"),new DataLoader(){

        // will be called once for each record in the file
        String processRecord(Record r){

            // if there's no "bar",invalid record
            if( ! r.hasField("bar") ){
                throw new BazException();
            }
            records.add(r);
        }
    });
    return records;
}

Solution

An exception means that the method can throw it instead of a class (someoneelse Library)@ H_ 301_ 4 @ there are two types of exceptions, checked (subtype of exception) and unchecked (subtype of runtimeException) Checked must be explicitly declared in the signature of the method that can throw it Unchecked can be propagated without being declared in the method's signature or processed without a try / catch block

public ArrayList<Record> foo(){
    static ArrayList<Record> records = new ArrayList<Record>();

    try{
       SomeoneElsesLibrary.loadData( ... );
    } catch (BazException be){ // you just handle the exception here
    }

    return records;
}
public ArrayList<Record> foo(){
    static ArrayList<Record> records = new ArrayList<Record>();

    // if SomeoneElsesLibrary.loadData raise the BazException
    // it is propagated to the caller of foo()
    SomeoneElsesLibrary.loadData( ... );

    return records;
}
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>