public class CD { public void setDetails (String type, String title, String artist) throws InvalidTypeException { if (type.equals("album") || type.equals("single")) { this.type = type; this.artist = artist; this.title = title; } else { throw new InvalidTypeException("Must be single or album!"); } } }
String type = (read in from user) String title = (read in from user) String artist = (read in from user) CD cd = new CD(); try { cd.setDetails (type, title, artist); System.out.println("Created CD successfully."); } catch (InvalidTypeException e) { System.out.println ("An error occurred: " + e); }
public class InvalidTypeException extends Exception
throw new InvalidTypeException("Must be single or album!");
public class InvalidTypeException extends Exception { String message; public InvalidTypeException (String m) { message = m; } public String toString() { return message; } }
Person p = null; // SHOULD BE Person p = new Person(); ! p.setName ("John");
try { // Not a real Java method - imagine this is a custom method we have written to // read in from file, hiding the complexities of file I/O readFromFile("myfile.dat"); } catch (FileNotFoundException e) { System.out.println("Input file myfile.dat could not be found!"); } catch (IOException e) { System.out.println("General input/output error - hard drive failure?"); }
catch (Exception e)will catch any exceptions not caught by the more specific catch blocks above
try { .... } catch (VerySpecificException e) { ... } catch (MoreGeneralException e) { .... } catch (Exception e) { .... }
DatabaseConnection connection = null; try { connection.connect(username, password); Results results = connection.query("SELECT * FROM songs"); // do something with the database results (not shown) } catch(DatabaseException sqlException) { out.println("Error: " + sqlException); } finally { if(connection != null) { connection.close(); } }