// Typical method that returns boolean value boolean success = checkIfDatabaseContainsPersonWithID(1); if(success) { System.out.println("we found a person from the database!"); } } public static boolean checkIfDatabaseContainsPersonWithID(int id) { // Connect to database -> Can Fail // Make query to database -> Can Fail // Inform by return true or false if person was found. } }
try { boolean success = checkIfDatabaseContainsPersonWithID(1); if(success) { System.out.println("we found a person from the database!"); } } catch(IOException e) { ... } } public static boolean checkIfDatabaseContainsPersonWithID(int id) throws IOException { // Connect to database -> If fails, throw IOException! // Make query to database -> If fails, throw IOException // Inform by return true or false if person was found. } }
try { int x = Integer.parseInt("xxx"); } catch(NumberFormatException e) { System.out.println("We have a problem casting the number"). } } } Method throws an exception
static void main(String [] args) { try { int a = Integer.parseInt(args[0]); String operator = args[1]; int b = Integer.parseInt(args[2]); switch(operator) { case "+": System.out.println(a + b); break; case "-": System.out.println(a - b); break; case "/": System.out.println(a / b); break; } } catch(Exception e) { System.out.println("Problem"); } } } All possible exceptions, not a recommendation!
} } class Main { public static void main(String [] args) { try { String operator = parseOperator("f"); } catch(OperatorException e) { // Must be +, -, or / System.out.println(e.getMessage()); } } public static String parseOperator(String isThisOperator) throws OperatorException { String [] operators = {"+", "-", "/"}; boolean success = false; for(String operator: operators) { if(operator.equals(isThisOperator)) { success = true; } } if(success) { return isThisOperator; } else { OperatorException ex = new OperatorException("Must be +, -, or /"); throw ex; } } } To give additional information about the Exception, you can use message
try { // Open connection to database -> can fail // Make querys to database -> can fail // => Connection will NOT be closed if this fails.. // Close the connection -> can fail } catch(Exception e) { } } }
try { // Open connection to database -> can fail // Make querys to database -> can fail // If you have return in here, it will exit the method! // => NO CLOSING! return; } catch(Exception e) { } // Close the connection -> can fail } }
try { // Open connection to database -> can fail // Make querys to database -> can fail // The finally is called event if we have "return" in here! return; } catch(Exception e) { } finally { // If connection was opened, close the connection } } }