Slide 1

Slide 1 text

Exception Handling in Java Jussi Pohjolainen

Slide 2

Slide 2 text

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); } }

Slide 3

Slide 3 text

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. } }

Slide 4

Slide 4 text

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. } }

Slide 5

Slide 5 text

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

Slide 6

Slide 6 text

// 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

Slide 7

Slide 7 text

// 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

Slide 8

Slide 8 text

// 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!

Slide 9

Slide 9 text

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

Slide 10

Slide 10 text

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

Slide 11

Slide 11 text

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!

Slide 12

Slide 12 text

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

Slide 13

Slide 13 text

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

Slide 14

Slide 14 text

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

Slide 15

Slide 15 text

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) { } } }

Slide 16

Slide 16 text

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 } }

Slide 17

Slide 17 text

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 } } }

Slide 18

Slide 18 text

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(); } } }

Slide 19

Slide 19 text

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!