Download presentation
Presentation is loading. Please wait.
Published byἈδράστεια Ελευθερίου Modified over 6 years ago
1
SWE 332 Last Modified Spring 2010 Paul Ammann
Java Exceptions SWE 332 Last Modified Spring 2010 Paul Ammann
2
Rationale for Exceptions
Preconditions document undefined behavior Undefined behavior Partial specification In any implementation, something happens Should clients rely on undocumented behavior? What happens in next release? Bottom line: Preconditions are usually undesirable But sometimes unavoidable… Exception handling: Transform preconditions to defined behavior One of several possible mechanisms…
3
Transforming a Precondition to an Exceptional Postcondition
Key: Postcondition defines behavior for inputs excluded by precondition public double sqrt (double x) // precondition: x >= 0 // postcondition: … // precondition: // postcondition: If x < 0 throw IllegalArgumentException // else … /** x the square of the intended result approximate square root of x… IllegalArgumentException if x < 0 */
4
Java Exception Mechanism
Checked Exceptions Unchecked Exceptions Ammann 2008
5
Exceptions Unchecked: client does not need to explicitly write special code Checked: client has to pay attention to these. Must write special code blocks Many different types of exceptions are provided. You can provide your own. Ammann 2008
6
Custom Exceptions public MyFavoriteException extends Exception {
super(); } public MyFavoriteException(String s) {super(s);} can add more like state at the time of throwing the exception methods that let the invalid state be printed and other useful information Ammann 2008
7
Throwing Exceptions Explicit throws
throw new NullPointerException(“”); throw new NPE(“class, method”); System throws String [ ] a = {“1”,”2”,”3”,”4”,”5”}; print(a[-1]); System throws IndexOutOfBoundsException Passing through (goes up the call chain) keeps going till it finds a handler Ammann 2008
8
Catching Exceptions In a special code block called try-block try{
}catch(ExceptionType instance){ } Ammann 2008
9
Catching Exceptions Can have multiple catch blocks, with different execution logic for different exceptions raised Class hierarchy matters in catching! If you catch an exception of type Exception, all subtypes are also caught! catching Exception is dangerous! WHY? Ammann 2008
10
Remember! try-catch block should be as short as possible.
catch the right type of exception: to be sure of what’s the right thing to do Ammann 2008
Similar presentations
© 2024 SlidePlayer.com Inc.
All rights reserved.