Upgrade to Pro — share decks privately, control downloads, hide ads and more …

Java Exceptions

Sponsored · Ship Features Fearlessly Turn features on and off without deploys. Used by thousands of Ruby developers.

Java Exceptions

Java Exceptions

Avatar for Jussi Pohjolainen

Jussi Pohjolainen

February 13, 2024
Tweet

More Decks by Jussi Pohjolainen

Other Decks in Technology

Transcript

  1. class Main { public static void main(String [] args) {

    // Typical method that returns boolean value boolean success = isItNumber("-12.0"); if(success) { System.out.println("It was a number!"); } } public static boolean isItNumber(String number) { String pattern = "^[-+]?[0-9]*\\.?[0-9]+([eE][-+]?[0-9]+)?$"; return number.matches(pattern); } }
  2. class Main { public static void main(String [] args) {

    // 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. } }
  3. class Main { public static void main(String [] args) {

    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. } }
  4. class Main { public static void main(String [] args) {

    try { int x = Integer.parseInt("xxx"); } catch(NumberFormatException e) { System.out.println("We have a problem casting the number"). } } } Method throws an exception
  5. // Java Main 1 / 0 class Main { public

    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(NumberFormatException e) { System.out.println("Please give integer numbers."); } catch(ArrayIndexOutOfBoundsException e) { System.out.println("Please give calculation, like 1 + 2."); } catch(ArithmeticException e) { System.out.println("Do not divide with zero."); } } } java Main ArrayIndexOutOfBoundsException java Main k + k NumberFormatException java Main 1 / 0 ArithmeticException
  6. // Java Main 1 + 2 class Main { public

    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(NumberFormatException | ArrayIndexOutOfBoundsException | ArithmeticException e) { System.out.println("Problem"); } } } Multicatch
  7. // Java Main 1 + 2 class Main { public

    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!
  8. java Main 1 k 2 class Main { public static

    void main(String [] args) { try { int a = Integer.parseInt(args[0]); String operator = parseOperator(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"); } } public static String parseOperator(String isThisOperator) throws Exception { String [] operators = {"+", "-", "/"}; boolean success = false; for(String operator: operators) { if(operator.equals(isThisOperator)) { success = true; } } if(success) { return isThisOperator; } else { Exception ex = new Exception(); throw ex; } } } Throwing your own exception
  9. class Main { public static void main(String [] args) {

    try { int a = Integer.parseInt(args[0]); String operator = parseOperator(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(OperatorException | NumberFormatException | ArrayIndexOutOfBoundsException | ArithmeticException e) { System.out.println("Problem"); } } ... 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(); throw ex; } } } class OperatorException extends Exception {} Creating your own exception
  10. class OperatorException extends Exception {} class Main { public static

    void main(String [] args) { // javac Main.java // UnreportedException; must be caught or declared to be thrown. String operator = parseOperator("+"); } 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(); throw ex; } } } If the exception class inherites Exception, you must write try .. catch. It won't compile otherwise!
  11. class OperatorException extends RuntimeException {} class Main { public static

    void main(String [] args) { // javac Main.java // Will compile. String operator = parseOperator("f"); } 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(); throw ex; } } } If the exception class inherites RuntimeException, you do NOT have to write try catc
  12. class OperatorException extends RuntimeException {} class Main { public static

    void main(String [] args) { // javac Main.java // Will compile. String operator = parseOperator("f"); } 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(); throw ex; } } } When using RuntimeException, you don't have declare throws
  13. class OperatorException extends RuntimeException { public OperatorException(String msg) { super(msg);

    } } 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
  14. class Main { public static void main(String [] args) {

    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) { } } }
  15. class Main { public static void main(String [] args) {

    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 } }
  16. class Main { public static void main(String [] args) {

    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 } } }
  17. FileWriter writer = null; try { writer = new FileWriter("example.txt");

    writer.write("Hello, without AutoCloseable!"); } catch (IOException e) { e.printStackTrace(); } finally { if (writer != null) { try { writer.close(); } catch (IOException e) { e.printStackTrace(); } } }
  18. try (FileWriter writer = new FileWriter("example.txt")) { writer.write("Hello, AutoCloseable!"); }

    catch (IOException e) { e.printStackTrace(); } try-with-resources will close the stream for you correctly!