Last active
August 29, 2015 14:13
-
-
Save AndreasHassing/d4f34d67dadc29e78b05 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package dk.itu.abhn.sandbox; | |
public class PlayWithBetterExceptions { | |
int[] someArray; | |
public PlayWithBetterExceptions() { | |
someArray = new int[]{1, 2, 3, 4, 5}; // array that is 5 elements long! | |
} | |
public static void main(String[] args) { | |
PlayWithBetterExceptions t = new PlayWithBetterExceptions(); | |
System.out.println(t.accessElementOutOfBounds(4)); // this is ok! Element 4 exists and = 5. | |
System.out.println(t.accessElementOutOfBounds(5)); // wow wow wow! calm down there.. no such element! | |
// No worries, we wont crash thanks to our method throwing the exception to a try..catch! | |
} | |
public int accessElementOutOfBounds(int elementNumber) throws ArrayIndexOutOfBoundsException { | |
try { | |
return someArray[elementNumber]; | |
} catch (ArrayIndexOutOfBoundsException e) { | |
System.out.println("Ok we failed, but at least we didnt crash! WOOP!"); | |
return -1; // print some stupid number to show that we failed! | |
} | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package dk.itu.abhn.sandbox; | |
public class PlayWithExceptions { | |
int[] someArray; | |
public PlayWithExceptions() { | |
someArray = new int[]{1, 2, 3, 4, 5}; // array that is 5 elements long! | |
} | |
public static void main(String[] args) { | |
PlayWithExceptions t = new PlayWithExceptions(); | |
System.out.println(t.accessElementOutOfBounds(4)); // this is ok! Element 4 exists and = 5. | |
System.out.println(t.accessElementOutOfBounds(5)); // wow wow wow! calm down there.. no such element! | |
// Thereafter the program simply crashes.. | |
} | |
public int accessElementOutOfBounds(int elementNumber) { | |
return someArray[elementNumber]; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment