Advanced Programming (02324) Spring 2025 PDF
Document Details
![IncredibleInequality5098](https://quizgecko.com/images/avatars/avatar-2.webp)
Uploaded by IncredibleInequality5098
DTU
2025
Carlos E. Budde and Ekkart Kindler
Tags
Summary
These are lecture slides from the Advanced Programming (02324) course for Spring 2025 by Carlos E. Budde and Ekkart Kindler from DTU. The slides cover topics such as exceptions, exception handling, and related programming concepts.
Full Transcript
Advanced Programming (02324) Spring 2025 Carlos E. Budde and Ekkart Kindler Part I (cntd.) 4. Exceptions Why exceptions at all? Carlos E. Budde and Ekkart Kindler Read contents of specified file, and return...
Advanced Programming (02324) Spring 2025 Carlos E. Budde and Ekkart Kindler Part I (cntd.) 4. Exceptions Why exceptions at all? Carlos E. Budde and Ekkart Kindler Read contents of specified file, and return the number of characters read. If there’s an error return a negative number, so the caller knows. Issues opening file? Return -1 Issues reading file? Return error code Convention: main files return 0 on success, and an error code > 0 on error. Advanced Programming (02324) f25, L03.1 4 Why exceptions at all? Carlos E. Budde and Ekkart Kindler Read contents of specified file, and return the number of characters read. If there’s an error return a negative number, so the caller knows. Convention: main files return 0 on success, and an error code > 0 on error. Advanced Programming (02324) f25, L03.1 5 Why exceptions at all? Carlos E. Budde and Ekkart Kindler Read contents of specified file, and return the number of characters read. If there’s an error return a negative number, so the caller knows. Convention: main files return 0 on success, and an error code > 0 on error. Advanced Programming (02324) f25, L03.1 6 Exceptions! Carlos E. Budde and Ekkart Kindler J Studios/Getty Images Advanced Programming (02324) f25, L03.1 7 Exceptions!! Carlos E. Budde and Ekkart Kindler ▪ Expose unexpected behaviour / errors, ▪ cannot be confused with “normal execution”. ▪ Alter the program control flow, reversing the calling stack: ▪ go back to caller, who goes back to caller, etc. Advanced Programming (02324) f25, L03.1 8 Exceptions!! Carlos E. Budde and Ekkart Kindler ▪ Expose unexpected behaviour / errors, ▪ cannot be confused with “normal execution”. ▪ Alter the program control flow, reversing the calling stack: ▪ go back to caller, who goes back to caller, etc. Advanced Programming (02324) f25, L03.1 9 Exceptions!!! Carlos E. Budde and Ekkart Kindler ▪ Expose unexpected behaviour / errors, ▪ cannot be confused with “normal execution”. ▪ Alter the program control flow, reversing the calling stack: ▪ go back to caller, who goes back to caller, etc. ▪ Who called the method that is throwing the exception can either catch or not: ▪ if we catch an exception, it’s because we can handle it; ▪ else, let it go upstairs so upper management takes care. ▪ When no one catches the exception… ▪ Methods declare if they (may) throw an exception. ▪ finally… comes to save the day and ruin (y)our lives. Advanced Programming (02324) f25, L03.1 10 Exception throwing Carlos E. Budde and Ekkart Kindler @Override This is badly-formatted code: public Integer pop() { no braces for body of if statement; if (size < 1) no else statement. return null; --size; return array[size]; } We declare what we throw public Integer rock() throws UnsupportedOperationException { if (size < 1 ) throw new UnsupportedOperationException(“Can’t pop empty Stack"); return array[--size]; Exception thrown in this line } What does new do? If we throw, normal flow is interrupted and we Why is it needed? start to go up, so the return is not executed (we all float) Advanced Programming (02324) f25, L03.1 11 Exception throwing Carlos E. Budde and Ekkart Kindler public void miusik() throws UnsupportedOperationException { System.out.println("Pop: ".concat(String.valueOf(pop()))); System.out.println("Rock: " + rock()); } We don’t throw explicitly, but an internal method may. How do we know?? throws indicates that we may throw, not that we surely will We declare what we throw public Integer rock() throws UnsupportedOperationException { if (size < 1 ) throw new UnsupportedOperationException(“Can’t pop empty Stack"); return array[--size]; Exception thrown in this line } Advanced Programming (02324) f25, L03.1 12 Exception catching Carlos E. Budde and Ekkart Kindler public void miusik() throws UnsupportedOperationException { System.out.println("Pop: ".concat(String.valueOf(pop()))); System.out.println("Rock: try { " + rock()); } System.out.println("Rock: " + rock()); } catch (UnsupportedOperationException e) { System.out.println("Heeeelp! " + e.getMessage()); } } How are we recovering here? Probably smarter to check if isEmpty() before calling rock()… just sayin’ try { // … dangerous code … } catch ( ) { // … try to recover, may manipulate } Advanced Programming (02324) f25, L03.1 13 Exception handling Carlos E. Budde and Ekkart Kindler try { // … dangerous code … Only run if thrown } catch ( ) { // … try to recover, may manipulate } catch ( ) { // … try to recover, may manipulate --. Only run if thrown } catch ( ) { // … try to recover, may manipulate } finally { Only run if thrown // do a flip before majestic exit } Always run! Whether exceptions occur or not Advanced Programming (02324) f25, L03.1 14 Exception handling Carlos E. Budde and Ekkart Kindler public Integer rock() { if (size < 1) throw new UnsupportedOperationException("can't pop empty Stack"); else if (size -= 1) throw new NullPointerException("catch me if you can"); return array[--size]; } public void concert() { try { System.err.println("\t[0:NORMAL] Rock is " + rock()); } catch (UnsupportedOperationException e) { System.err.print("\t[1:ALT] Don't be silly, “ + e.getMessage()); System.err.println("--. but we let it pass"); } catch (NullPointerException e) { System.err.println("\t[2:HARD] Can't fix \"“ + e.getMessage() + "\""); throw e; } finally { System.err.println("\t[FINALLY] My job here is done"); } System.err.println("\t[3:END] End of concert"); } Advanced Programming (02324) f25, L03.1 15 Exception handling Carlos E. Budde and Ekkart Kindler public Integer rock() { if (size < 1) throw new UnsupportedOperationException("can't pop empty Stack"); else if (size -= 1) throw new NullPointerException("catch me if you can"); return array[--size]; } public void concert() { try { System.err.println("\t[0:NORMAL] Rock is " + rock()); } catch (UnsupportedOperationException e) { We can re-throw an exception caught… System.err.print("\t[1:ALT] Don't be silly, “ + e.getMessage()); System.err.println("--. but we let it pass"); But what use is this? } catch (NullPointerException e) { System.err.println("\t[2:HARD] Can't fix \"“ + e.getMessage() + "\""); throw e; } finally { System.err.println("\t[FINALLY] My job here is done"); } System.err.println("\t[3:END] End of concert"); Always run! } Advanced Programming (02324) f25, L03.1 16 Exception handling Carlos E. Budde and Ekkart Kindler @Test Normal rock() public void soundTest() { [0:NORMAL] Rock is 1 ArrayStack astack = (ArrayStack) stack; [FINALLY] My job here is done // [3:END] End of concert System.err.println("Normal rock()"); Alt rock() astack.push(1); [1:ALT] Don't be silly, can't pop empty Stack... but we let it p astack.push(1); [FINALLY] My job here is done astack.concert(); [3:END] End of concert But that was // System.err.println("Alt rock()"); Hard rock() undeclared !? try { [2:HARD] Can't fix "catch me if you can" astack.clear(); [FINALLY] My job here is done astack.concert(); >>> Caught "java.lang.NullPointerException: catch me if you ca } catch (UnsupportedOperationException e) { System.err.println("--> Caught \"" + e + "\""); public void concert() { } try { // System.err.println("\t[0:NORMAL] Rock is “ + rock() System.err.println("Hard rock()"); } catch (UnsupportedOperationException e) { try { System.err.print("\t[1:ALT] Don't be silly, “ + e.g Assert.assertTrue(astack.isEmpty()); System.err.println("--. but we let it pass”); astack.push(1); How did this } catch (NullPointerException e) { System.err.println("\t[2:HARD] Can't fix \"“ + e.ge astack.concert(); catch it? throw e; } catch (Exception e) { } finally { System.err.println("--> Caught \"" + e + "\""); System.err.println("\t[FINALLY] My job here is done } } } System.err.println("\t[3:END] End of concert"); } Advanced Programming (02324) f25, L03.1 17 Exceptions hierarchy Carlos E. Budde and Ekkart Kindler Program Program must can let float Throwable declare, to catch Checked Exceptions Reflective- Error Exception Operation- Exception SQLException … IOError StackOverflowError RuntimeException IOException OutOfMemoryError … IllegalArgumentException FileNotFoundException Unchecked NullPointerException EOFException Exceptions IndexOutOfBoundsException … … Advanced Programming (02324) f25, L03.1 18 Your own Exceptions Carlos E. Budde and Ekkart Kindler public class MyException extends Exception { MyException(String msg) { super(msg); } MyException(String msg, Exception e) { super(msg, e); } } Checked (must declare) Not necessarily the best, if we can refine: Unchecked … extends IOException { … (can ignore) … extends Error { … Java's documentation: If a client can reasonably be expected to recover from an exception, make it a … extends RuntimeException { … checked exception. If a client cannot do anything to recover from the exception, make it an unchecked exception. Advanced Programming (02324) f25, L03.1 19 Re-throwing Carlos E. Budde and Ekkart Kindler try { // something that may throw Can be used for “positive” } catch (Exception e) { connotations! E.g. print: “You won! Please // cleanup of sorts, enter credit card number: ” // print warning throw e; Vs: } … } catch (Exception e) { // cleanup of sorts throw new MyException("lol", e); } Advanced Programming (02324) f25, L03.1 20 Advanced Programming (02324) Spring 2025 Carlos E. Budde and Ekkart Kindler