1
Nested Classes
2
Nested Classes
• Possible to declare a class within another class;
called nested classes
• Nested class should have some specific
association with the enclosing class, otherwise not
sensible to do so
• Can be static or non-static
• A non-static nested class is called an inner class
public class Outside { //top-level class
public class Inside{//nested class
//details of Inside class…
}
//more members of Outside class…
}
3
Nested Classes
• An inner class (i.e. non-static) has access to all the
variables and methods of its outer class and may
refer to them directly in the same way that other
non-static members of the outer class do
• Reverse not true
• Static nested classes seldom used because they
can only access members of the enclosing class
through an object, rather than directly
• Methods of outer class can create objects of inner
class. Outer class is responsible for creating inner
class objects
4
Nested Classes
class Outer {
int outer_x = 100;
void test() {
Inner inner = new Inner();
[Link]();
}
// this is an inner class
class Inner {
int y = 10; // y is local to Inner
void display() {
[Link]("display: outer_x = " + outer_x);
}
}
/* void showy() {
[Link](y); // error, y not known here!
} */
}
class InnerClassDemo {
public static void main(String args[]) {
Outer outer = new Outer();
[Link]();
}
}
Output: display: outer_x = 100
5
Nested Classes
• Or in class InnerClassDemo’s main( ):
Outer o = new Outer ( );
[Link] i = [Link] Inner ( ); /* enclosing class
name used as qualifier */
[Link]( ); //same output now
• We create an object of inside class in the context
of an outer class’s object
• A nested class can have an access attribute
(public, private, protected, default) just like
other class members, and the accessibility from
outside the enclosing class is determined by the
attributes in the same way
6
Nested Classes
• What are the access attributes for normal classes?
e.g. if we make private class Inner then not
accessible from InnerClassDemo
• Inside any block: Can have inner classes within
any block scope e.g. methods or even a for loop
(the inner class now cannot have any access
specifier)
• When so defined, inner class can access only final
local variables or method parameters that are in
the scope of the block that declares the class
7
Exception Handling
8
Introduction
• Errors can be dealt with at place error occurs
– Easy to see if proper error checking implemented
– Harder to read application itself and see how code works
• Exception handling
– Makes clear, robust, fault-tolerant programs
– Java removes error handling code from "main line" of program
• Common failures
– Out of bounds array subscript
– Division by zero
– Memory exhaustion
– Invalid method parameters
9
Introduction
• Exception handling
– Catch errors before they occur
– Used when system can recover from error
• Exception handler - recovery procedure
• Error dealt with in different place than where it occurred
– Useful when program cannot recover but must shut down
cleanly
10
When Exception Handling
Should Be Used
• Exception handling used for
– Processing exceptional situations where a method is unable
to complete task for reasons beyond its control
– Processing exceptions for components (methods, libraries,
classes) that are to be widely used and that cannot handle
them directly (unique needs of each user)
– Large projects that require project wide uniform error
processing
11
The Basics of Java Exception
Handling
• Exception handling
– Java exception is an object
– Built-in class Throwable is superclass of all exception
subclasses
– 2 subclasses of Throwable: Exception and Error
– User generated errors handled by Exception — extend it to
create your own exception types
– Run-time environment errors by Error (will not cover) e.g.
stack overflow, or JVM error
– Method detects error it cannot deal with
• Throws an exception
– Exception handler
• Code to catch exception and handle it
12
The Basics of Java Exception
Handling
• Useful to see what happens when you don’t handle
exceptions in your program
class Exc0 {
public static void main(String args[]) {
int d = 0;
int a = 42 / d;
}
}
Output from default exception handler:
Exception in thread “main”
[Link]: / by zero
at [Link]([Link])
13
The Basics of Java Exception
Handling
• Format
– Enclose code that may have an error in try block
– Follow with one or more catch blocks
• Each catch block has an exception handler
– On exception, try block exited (and not returned to)
– If exception occurs and matches parameter in catch block
• Code in catch block executed
– If no exception thrown
• Exception handling code skipped
• Control resumes after catch blocks
try{
code that may throw exceptions
}
catch (ExceptionType ref) {
exception handling code
}
14
The Basics of Java Exception
Handling
• Java uses Termination model of exception handling
(cf Resumption model)
– throw point
• Place where exception occurred – can be from statements in a
method, or from a called method in at try block
• Control cannot return to throw point
– Block which threw exception expires
• Key to Java exception handling is that the exception
handler can be distant from the exception generating
code
15
An Exception Handling Example:
Divide by Zero
• Example program
– We want to catch division by zero errors
– Exceptions
• Objects derived from class Exception
– Look in Exception classes in [Link]
• Subclass RuntimeException has exceptions automatically
defined for your program and include divide by zero
• ArithmeticException extends RuntimeException
and handles divide by zero for integers. If float, Java allows it by
positive or negative infinity. Can still handle by writing your own
extended class
public class MyException extends ArithmeticException{…}
16
An Exception Handling Example:
Divide by Zero
class Exc2 {
public static void main(String args[]) {
int d, a;
try { // monitor a block of code.
d = 0;
a = 42 / d;
[Link]("This will not be printed.");
} catch (ArithmeticException e) { // catch divide-
//by-zero error
[Link]("Division by zero.");
}
[Link]("After catch statement.");
}
}
• Output:
Division by zero.
After catch statement.
17
Catching an Exception
• Catching exceptions
– To catch all exceptions, catch an exception object:
catch( Exception e )
– First handler to catch exception does
• All other handlers skipped
– If exception not caught
• Searches enclosing try blocks for appropriate handler
try{
try{
throw Exception2
}
catch ( Exception1 ){...}
}
catch( Exception2 ){...}
– If still not caught, default exception handler runs
18
Multiple catch Clauses
// Demonstrate multiple catch statements.
class MultiCatch {
public static void main(String args[]) {
try {
int a = [Link];
[Link]("a = " + a);
int b = 42 / a;
int c[] = { 1 };
c[42] = 99;
} catch(ArithmeticException e) {
[Link]("Divide by 0: " + e);
} catch(ArrayIndexOutOfBoundsException e) {
[Link]("Array index oob: " + e);
}
[Link]("After try/catch blocks.");
}
}
19
Multiple catch Clauses
• Exception subclasses before any superclass. Otherwise
unreachable code compile time error.
class SuperSubCatch {
public static void main(String args[]) {
try {
int a = 0;
int b = 42 / a;
} catch(Exception e) {
[Link]("Generic Exception catch.");
}
/* This catch is never reached because
ArithmeticException is a subclass of Exception. */
catch(ArithmeticException e) { // ERROR - unreachable
[Link]("This is never reached.");
}
}
}
20
Nested try Statements
class NestTry { /* If two command line args are used
public static void main(String args[]) { then generate an out-of-bounds
try { exception. */
int a = [Link]; if(a = =2) {
int c[ ] = { 1 };
/* If no command line args are present, c[42] = 99; /* generate an out-of-bounds
exception */
the following statement will generate
}
a divide-by-zero exception. */
}//end of inner try
int b = 42 / a; catch(ArrayIndexOutOfBoundsException e)
{
[Link]("a = " + a); [Link]("Array index out-of-
bounds: " + e);
try { // nested try block }
/* If one command line arg is used,
then a divide-by-zero exception } catch(ArithmeticException e) {
will be generated by the following [Link]("Divide by 0: " + e);
code. */ }
if(a= =1) a = a/(a-a); // division by zero }
}
21
/* Try statements can be implicitly public static void main(String args[]) {
nested via try {
calls to methods. */ int a = [Link];
class MethNestTry { int b = 42 / a;
static void nesttry(int a) { [Link]("a = " + a);
try { // nested try block nesttry(a);
if(a= =1) a = a/(a-a); // division } catch(ArithmeticException e) {
//by zero
[Link]("Divide by 0: "
if(a= =2) { + e);
int c[] = { 1 }; }
c[42] = 99; // generate an out-of- }
bounds exception
}
}
}
catch(ArrayIndexOutOfBoundsExc
eption e) {
[Link]("Array index
out-of-bounds: " + e);
}
}
22
Throwing an Exception
• throw
– So far have seen exceptions thrown by the Java run-time
system
– Can throw an exception explicitly too
– throw ThrowableInstance;
• Object of any class derived from Throwable
e.g. throw new MyException();
• When exception thrown
– Control exits current try block
– Proceeds to catch handler (if exists)
23
class ThrowDemo {
static void demoproc() {
try {
throw new NullPointerException("demo");
} catch(NullPointerException e) {
[Link]("Caught inside
demoproc.");
throw e; // re-throw the exception
}
}
public static void main(String args[]) {
try {
demoproc();
} catch(NullPointerException e) {
[Link]("Recaught: " + e);
}
}
}
Output: Caught inside demoproc.
Recaught: [Link]:
demo
24
Rethrowing an Exception
• Rethrowing exceptions
– Use if handler cannot process exception
– Rethrow exception with the statement:
throw e;
• Detected by next enclosing try block
– Handler can always rethrow exception, even if it performed
some processing
25
throws Clause
• Checked Exceptions:
– All non-RuntimeExceptions and all non-Error exceptions
• If a method is capable of causing a checked exception that
it does not catch itself, it must use a throws clause
type methodName(parameter list) throws exception list{…}
• If a method calls another method that explicitly throws
such exceptions, the calling method’s throws clause must
include those exceptions or the calling method must catch
those exceptions
• A method that overrides a subclass method cannot list
more exceptions in the throws clause than in the superclass
method (has to be a subset)
26
throws Clause
class ThrowsDemo {
static void throwOne() throws IllegalAccessException
{
[Link]("Inside throwOne.");
throw new IllegalAccessException("demo");
}
public static void main(String args[]) {
try {
throwOne();
} catch (IllegalAccessException e) {
[Link]("Caught " + e);
}
}
}
• Output: inside throwOne
Caught [Link]: demo
27
finally Block
• finally block
– Placed after last catch block
– Always executed, regardless whether exceptions thrown or
not thrown or caught i.e. always executed at the conclusion
of the try/catch block
– If catch blocks there, finally block executed after them
– Must be there if no catch block
– Ideal place for code that releases resources
– If exception thrown in finally block, processed by
enclosing try block
class FinallyDemo { 28
// Through an exception out of the method.
static void procA( ) {
try {
[Link]("inside procA"); public static void main(String args[ ]) {
throw new RuntimeException("demo"); try {
} finally { procA( );
[Link]("procA's finally"); } catch (Exception e) {
} [Link]("Exception caught");
} }
// Return from within a try block. procB();
static void procB( ) { procC();
try { }
[Link]("inside procB"); }
return; Output:
} finally { inside procA
[Link]("procB's finally"); procA’s finally
} Exception caught
} inside procB
// Execute a try block normally. procB’s finally
static void procC( ) { inside procC
try { procC’s finally
[Link]("inside procC");
} finally {
[Link]("procC's finally");
}
}
29
1 // Fig. 14.9: [Link] Outline
2 // Demonstration of stack unwinding.
3 public class UsingExceptions {
4 public static void main( String args[] )
5 { 1. main
6 try { Call method throwException
7 throwException(); (enclosed in a try block).
8 } 1.1 throwException
9 catch ( Exception e ) {
10 [Link]( "Exception handled inThrow
main"an
);Exception. The catch block
1.2 catch
11 } cannot handle it, but the finally block
12 } executes irregardless.
13 2. Define
14 public static void throwException() throws Exception throwException
15 {
16 // Throw an exception and catch it in main.
17 try { 2.1 try
18 [Link]( "Method throwException" );
19 throw new Exception(); // generate exception
20 }
2.2 catch
21 catch( RuntimeException e ) { // nothing caught here
22 [Link]( "Exception handled in " + 2.3 finally
23 "method throwException" );
24 }
25 finally {
26 [Link]( "Finally is always executed" );
27 }
28 }
29 }
2000 Prentice Hall, Inc. All rights reserved.
30
Outline
Method throwException
Finally is always executed
Exception handled in main Program Output
2000 Prentice Hall, Inc. All rights reserved.
31
Creating Your Own Exception
Subclasses
• To handle specific situations not covered by built-
in exceptions
• Extend Exception or some other subclass of it
32
class MyException extends Exception { public static void main(String
private int detail; args[]) {
MyException(int a) { try {
detail = a; compute(1);
} compute(20);
public String toString() {/*override } catch (MyException e) {
this method of Throwable*/ [Link]("Caught " +
return "MyException[" + detail + "]"; e);
} }
} }
class ExceptionDemo { }
static void compute(int a) throws Output:
MyException { Called compute(1)
[Link]("Called Normal exit
compute(" + a + ")");
Called compute(20)
if(a > 10)
Caught MyException[20]
throw new MyException(a);
[Link]("Normal exit");
}