Chapter5
Un article de Sometimes Kitties Think Too.
Sommaire |
[modifier]
Chapter 5 - Flow Control, Exceptions, Assertions
[modifier]
Flow Control
[modifier]
If/Else/Then Statements
+ curly braces are optional when there's only one statement
+ else will belong to innermost if-clause if curly brackets don't specify
+ non-boolean assignments don't work as if-clause tests
e.g. if (x = 4) --> results in if (4) which is illegal
[modifier]
Switch Statement
+ break statements are optional
+ general form:
switch (expression)
{
case constant1: code block
case constant2: code block
default: code block
}
+ switch statement must evaluate to a "char, byte, short, int or enum"
+ only variables that can be implicitly cast to an int
!! case constant must evaluate to switch expression constant AT COMPILE TIME!!
+ Compile-time constant expressions are used in case labels in switch statements
+ Wrapper classes (even final/static) cannot be case constants
+ the case variable must be a constant or a final
+ it is illegal to have a case statement that is larger than the switch argument
e.g. an int vs a byte
+ cannot have more than one case statement using the same value
+ auto-boxing is okay in the switch expression
+ if a method with a return value relies on a switch statement to return a value, then
the case statements must have "return"s or "throw"
Break & Fall-Through
+ first matching case statement is considered the "entry point"
+ all subsequent code blocks are executed after the entry point
Default Case
+ doesn't have to come at the end of the other case statements
+ works like any other case for fall-through
Examples of compile-time constant expressions:
true
(short)(1*2*3*4*5*6)
Integer.MAX_VALUE / 2
2.0 * Math.PI
"The integer " + Long.MAX_VALUE + " is mighty big."
[modifier]
Loops & Iterators
While Loop
+ good for executing an unpredetermined number of times
Do Loops
+ execute at least once before condition is tested
For Loops
for (/declare/initialize variables/; /conditional/ ; /iteration/) {
/* body */
}
+ the iteration expression and conditional test are always evaluated before exit
+ early loop termination can happen for the following reasons:
break - jumps to first statement after loop
return - jumps back to calling method
System.exit() - VM shuts down
continue - stops just the current iteration
+ none of the 3 sections is required
Enhanced For Loop
+ loops through arrays/collections
for (declaration : expressions)
/* body */
declaration - type compatible with elements of array being accessed.
Must be newly declared!
expression - evaluates to the array that needs to be looped through
Labeled Statements
[modifier]
Handling Exceptions
Finally
+ code always executed after the try block and/or catch block
+ catch block not required if there is a finally
legal:
try {
// do stuff
} finally {
// clean up
}
Propogating Uncaught Exceptions
+ if the catch blocks don't catch the exception it propogates
up the stack to main
Defining Exceptions
+ subclass of java.lang.Exception
Object
|
V
java.lang.Throwable
/ \
/ \
V V
java.lang.Error Exception
/
/
V
RuntimeException
+ throw can throw Exceptions, Errors, RuntimeExceptions
+ ClassCastException only occurs when you are casting reference types.
[modifier]
Exception Declaration
+ any method that might throw an exception (unless it's a subclass of
RuntimeException) must declare
+ all non-runtime exceptions are checked exceptions
+ each method must handle checked exceptions (with catch clause)
or list unhandled checked exception as a thrown exception
+ checked exceptions refers to the compiler verifying the throw-or-catch principle
+ unchecked exceptions are RuntimeExceptions or their children
"handle or declare"
declare: "void doMore() throws IOException {...}"
handle: try {...} catch () {...}
+ no point in catching errors
+ throwing an error: throw new Error();
[modifier]
Rethrowing Exceptions
+ can't rethrow an exception unless you declare it
[modifier]
Common Exceptions/Errors
+ 2 types of exceptions: JVM and Programmatic
Programmatic (created by application or API) -- checked
+ AssertionError
+ IllegalArgumentException
+ IllegalStateException
+ NumberFormatException
+ IOException
+ FileNotFoundException
JVM -- unchecked, RuntimeExceptions
+ NullPointerException
+ StackOverflowError
+ ArrayIndexOutOfBoundsException
+ ClassCastException
+ ExceptionInInitializerError
+ NoClassDefFoundError
+ ArithmeticException
+ Error
(again, these are subclasses of java.lang.RuntimeException or java.lang.Error)
[modifier]
Assertion Mechanism
+ starting with 1.4, it's a debugging mechanism
+ assertions are inactive unless turned on
+ when incorrect assertion, throw AssertionError
format --> assert ( Expression1 ) : Expression2;
+ Expression1 returns a boolean value
+ Expression2 returns a value (usually String or int)
+ unless assertons are enabled, they are ignored by the JVM
[modifier]
Compiling w/ Asssertions
javac -source 1.4 <class>.java
+ this means that "assert" is considered a keyword
[modifier]
Running with Assertions
java -ea <class>
java -enableassertions <class>
+ to disable,
java -da <class>
+ to selectively disable
java -ea -da:<class>
+ java -ea -dsa --> Enable assertions in general, but disable assertions in system classes.
not illegal but inadviseable
+ don't catch assertions
+ don't use assertions in public code
+ don't use assertions that cause side-effects
[modifier]
Questions
1. if an exception is propogated to the main thread and crashes, does the "finally" block execute?
Yes, it executes before the crash
2. Unclear about the differences between thrown/checked exceptions...
