Java Exception Notes

Try-Catch-Finally

public static void copyTextFile(String originalFileName, String copyFileName)
{
    BufferedReader ifStream = null;
    PrintWriter ofStream = null;
    
    //try opening the file and do something with it
    try {
        ifStream = new BufferedReader( new FileReader(originalFileName) );
        ofStream = new PrintWriter(new FileWriter(copyFileName) );
        String line;
        
        while( (line=ifStream.readLine())!=null ) {
            ofStream.println(line);
        }
    }

    //catch exception
    catch (IOException e) {
        System.out.println("Error copying file");
    }
    
    //closes the stream even a exception is thrown
    finally {
        try {
            ifStream.close();
            ofStream.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

Throw

//defining your own exception class
class SomeException extends Exception {
    public SomeException(String message) {
        super(message);
    }
}

//example method
public methodName() throws SomeException {
    ...
    throw new SomeException(message);
}