Download presentation
Presentation is loading. Please wait.
1
1 Nested Classes O
2
2 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
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
4 Nested Classes class Outer { int outer_x = 100; void test() { Inner inner = new Inner(); inner.display(); } // this is an inner class class Inner { int y = 10; // y is local to Inner void display() { System.out.println("display: outer_x = " + outer_x); } /* void showy() { System.out.println(y); // error, y not known here! } */ } class InnerClassDemo { public static void main(String args[]) { Outer outer = new Outer(); outer.test(); } Output: display: outer_x = 100
5
5 Nested Classes Or in class InnerClassDemo’s main( ): Outer o = new Outer ( ); Outer.Inner i = o.new Inner ( ); /* enclosing class name used as qualifier */ i.display( ); //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
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
7 Exception Handling O
8
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
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
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
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
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” java.lang.ArithmeticException: / by zero at Exc0.main(Exc0.java:4)
13
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
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
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 java.lang 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
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; System.out.println("This will not be printed."); } catch (ArithmeticException e) { // catch divide- //by-zero error System.out.println("Division by zero."); } System.out.println("After catch statement."); } Output: Division by zero. After catch statement.
17
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 –If still not caught, default exception handler runs try{ try{ throw Exception2 } catch ( Exception1 ){...} } catch( Exception2 ){...}
18
18 Multiple catch Clauses // Demonstrate multiple catch statements. class MultiCatch { public static void main(String args[]) { try { int a = args.length; System.out.println("a = " + a); int b = 42 / a; int c[] = { 1 }; c[42] = 99; } catch(ArithmeticException e) { System.out.println("Divide by 0: " + e); } catch(ArrayIndexOutOfBoundsException e) { System.out.println("Array index oob: " + e); } System.out.println("After try/catch blocks."); }
19
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) { System.out.println("Generic Exception catch."); } /* This catch is never reached because ArithmeticException is a subclass of Exception. */ catch(ArithmeticException e) { // ERROR - unreachable System.out.println("This is never reached."); }
20
20 Nested try Statements class NestTry { public static void main(String args[]) { try { int a = args.length; /* If no command line args are present, the following statement will generate a divide-by-zero exception. */ int b = 42 / a; System.out.println("a = " + a); try { // nested try block /* If one command line arg is used, then a divide-by-zero exception will be generated by the following code. */ if(a= =1) a = a/(a-a); // division by zero /* If two command line args are used then generate an out-of-bounds exception. */ if(a = =2) { int c[ ] = { 1 }; c[42] = 99; /* generate an out-of-bounds exception */ } }//end of inner try catch(ArrayIndexOutOfBoundsException e) { System.out.println("Array index out-of- bounds: " + e); } } catch(ArithmeticException e) { System.out.println("Divide by 0: " + e); }
21
21 /* Try statements can be implicitly nested via calls to methods. */ class MethNestTry { static void nesttry(int a) { try { // nested try block if(a= =1) a = a/(a-a); // division //by zero if(a= =2) { int c[] = { 1 }; c[42] = 99; // generate an out-of- bounds exception } } catch(ArrayIndexOutOfBoundsExc eption e) { System.out.println("Array index out-of-bounds: " + e); } public static void main(String args[]) { try { int a = args.length; int b = 42 / a; System.out.println("a = " + a); nesttry(a); } catch(ArithmeticException e) { System.out.println("Divide by 0: " + e); }
22
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
23 class ThrowDemo { static void demoproc() { try { throw new NullPointerException("demo"); } catch(NullPointerException e) { System.out.println("Caught inside demoproc."); throw e; // re-throw the exception } public static void main(String args[]) { try { demoproc(); } catch(NullPointerException e) { System.out.println("Recaught: " + e); } Output: Caught inside demoproc. Recaught: java.lang.NullPointerException: demo
24
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
25 throws Clause Checked Exceptions: –All non- RuntimeException s 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
26 throws Clause class ThrowsDemo { static void throwOne() throws IllegalAccessException { System.out.println("Inside throwOne."); throw new IllegalAccessException("demo"); } public static void main(String args[]) { try { throwOne(); } catch (IllegalAccessException e) { System.out.println("Caught " + e); } Output: inside throwOne Caught java.lang.IllegalAccessException: demo
27
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
28
28 class FinallyDemo { // Through an exception out of the method. static void procA( ) { try { System.out.println("inside procA"); throw new RuntimeException("demo"); } finally { System.out.println("procA's finally"); } // Return from within a try block. static void procB( ) { try { System.out.println("inside procB"); return; } finally { System.out.println("procB's finally"); } // Execute a try block normally. static void procC( ) { try { System.out.println("inside procC"); } finally { System.out.println("procC's finally"); } public static void main(String args[ ]) { try { procA( ); } catch (Exception e) { System.out.println("Exception caught"); } procB(); procC(); } Output: inside procA procA’s finally Exception caught inside procB procB’s finally inside procC procC’s finally
29
2000 Prentice Hall, Inc. All rights reserved. Outline 29 1. main 1.1 throwException 1.2 catch 2. Define throwException 2.1 try 2.2 catch 2.3 finally 1// Fig. 14.9: UsingExceptions.java 2// Demonstration of stack unwinding. 3public class UsingExceptions { 4 public static void main( String args[] ) 5 { 6 try { 7 7 throwException(); 8 } 9 catch ( Exception e ) { 10 System.err.println( "Exception handled in main" ); 11 } 12 } 13 14 public static void throwException() throws Exception 15 { 16 // Throw an exception and catch it in main. 17 try { 18 System.out.println( "Method throwException" ); 19 19 throw new Exception(); // generate exception 20 } 21 catch( RuntimeException e ) { // nothing caught here 22 System.out.println( "Exception handled in " + 23 "method throwException" ); 24 } 25 finally { 26 System.err.println( "Finally is always executed" ); 27 } 28 } 29} Call method throwException (enclosed in a try block). Throw an Exception. The catch block cannot handle it, but the finally block executes irregardless.
30
2000 Prentice Hall, Inc. All rights reserved. Outline 30 Program Output Method throwException Finally is always executed Exception handled in main
31
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
32 class MyException extends Exception { private int detail; MyException(int a) { detail = a; } public String toString() {/*override this method of Throwable*/ return "MyException[" + detail + "]"; } class ExceptionDemo { static void compute(int a) throws MyException { System.out.println("Called compute(" + a + ")"); if(a > 10) throw new MyException(a); System.out.println("Normal exit"); } public static void main(String args[]) { try { compute(1); compute(20); } catch (MyException e) { System.out.println("Caught " + e); } Output: Called compute(1) Normal exit Called compute(20) Caught MyException[20]
Similar presentations
© 2024 SlidePlayer.com. Inc.
All rights reserved.