1 Nested Classes O. 2 Possible to declare a class within another class; called nested classes Nested class should have some specific association with.

Slides:



Advertisements
Similar presentations
Exceptions Chapter Throwing and Catching Exceptions When a program runs into a problem that it cannot handle, it throws an exception. Exceptions.
Advertisements

Exception Handling. Introduction Errors can be dealt with at place error occurs –Easy to see if proper error checking implemented –Harder to read application.
Exception Handling The purpose of exception handling is to permit the program to catch and handle errors rather than letting the error occur and suffer.
Exception Handling Chapter 15 2 What You Will Learn Use try, throw, catch to watch for indicate exceptions handle How to process exceptions and failures.
 2003 Prentice Hall, Inc. All rights reserved. Chapter 15 – Exception Handling Outline 15.1 Introduction 15.2 Exception-Handling Overview 15.3 Exception-Handling.
Index Exception handling Exception In Java Exception Types
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved Chapter 13 Exception Handling.
Exception Handling Yaodong Bi Exception Handling Java exception handling Try blocks Throwing and re-throwing an exception Catching an.
MIT-AITI Lecture 14: Exceptions Handling Errors with Exceptions Kenya 2005.
Exception Handling 1 CISC6795, Spring Introduction 2 Exception – an indication of a problem that occurs during a program’s execution, for examples:
 2002 Prentice Hall, Inc. All rights reserved. Chapter 14 – Exception Handling Outline 14.1 Introduction 14.2 When Exception Handling Should Be Used 14.3.
COMP201 Java Programming Topic 6: Exceptions Reading: Chapter 11.
Slides prepared by Rose Williams, Binghamton University ICS201 Exception Handling University of Hail College of Computer Science and Engineering Department.
Sadegh Aliakbary Sharif University of Technology Fall 2010.
Exception Handling. Introduction An exception is an abnormal condition that arises in a code sequence at run time. In computer languages that do not support.
1 Lecture 11 Interfaces and Exception Handling from Chapters 9 and 10.
1. 2 Examples for Exception?... An exception is an abnormal condition that arises in a code sequence at run time (Run time error). In other computer languages.
1 Lecture 4 Exception Handling. 2 Exception-Handling Fundamentals An exception is an abnormal condition that arises in a code sequence at run time A Java.
 2000 Prentice Hall, Inc. All rights reserved. 1 Chapter 14 - Exception Handling Outline 14.1Introduction 14.2When Exception Handling Should Be Used 14.3Other.
Exceptions in Java Fawzi Emad Chau-Wen Tseng Department of Computer Science University of Maryland, College Park.
Chapter 11: Handling Exceptions and Events J ava P rogramming: From Problem Analysis to Program Design, From Problem Analysis to Program Design, Fourth.
1 Lecture#8: EXCEPTION HANDLING Overview l What exceptions should be handled or thrown ? l The syntax of the try statement. l The semantics of the try.
Exceptions. Many problems in code are handled when the code is compiled, but not all Some are impossible to catch before the program is run  Must run.
1 Web Based Programming Section 6 James King 12 August 2003.
Chapter 13 Exception Handling F Claiming Exceptions F Throwing Exceptions F Catching Exceptions F Rethrowing Exceptions  The finally Clause F Cautions.
Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved Chapter 18 Exception Handling.
1 Chapter 14 - Exception Handling Outline 14.1Introduction 14.2When Exception Handling Should Be Used 14.3Other Error Handling Techniques 14.4The Basics.
Object Oriented Programming
06 Exception Handling. 2 Contents What is an Exception? Exception-handling in Java Types of Exceptions Exception Hierarchy try-catch()-finally Statement.
EXCEPTION HANDLING.
Exception Handling in Java Exception Handling Introduction: After completing this chapter, you will be able to comprehend the nature and kinds.
Java Programming Exception Handling. The exception handling is one of the powerful mechanism provided in java. It provides the mechanism to handle the.
Object Oriented Programming with Java (150704).  Throwable Exception (This class will catch exceptions generated by prog.) (Create your own custom exception.
Slides Credit Umair Javed LUMS Web Application Development.
Exception Handling in JAVA. Introduction Exception is an abnormal condition that arises when executing a program. In the languages that do not support.
Exception Handling Unit-6. Introduction An exception is a problem that arises during the execution of a program. An exception can occur for many different.
Android How to Program, 2/e © Copyright by Pearson Education, Inc. All Rights Reserved.
Exceptions in Java. Exceptions An exception is an object describing an unusual or erroneous situation Exceptions are thrown by a program, and may be caught.
BIO Java 1 Exception Handling Aborting program not always a good idea – can’t lose messages – E-commerce: must ensure correct handling of private.
Data Structures Using Java1 Chapter 2 Inheritance and Exception Handling.
Sheet 3 HANDLING EXCEPTIONS Advanced Programming using Java By Nora Alaqeel.
Java Programming: From Problem Analysis to Program Design, 4e Chapter 11 Handling Exceptions and Events.
Unit 4 School of Information Systems & Technology1 School of Information Systems and Technology (IST)
 2000 Prentice Hall, Inc. All rights reserved. 1 Chapter 14 - Exception Handling Outline 14.1Introduction 14.2When Exception Handling Should Be Used 14.3Other.
Exception Handling in Java Topics: Introduction Errors and Error handling Exceptions Types of Exceptions Coding Exceptions Summary.
Exceptions in Java. What is an exception? An exception is an error condition that changes the normal flow of control in a program Exceptions in Java separates.
© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. Chapter 23 - Exception Handling Outline 23.1Introduction.
Exception Handling Outline 23.1 Introduction
CS212: Object Oriented Analysis and Design Lecture 19: Exception Handling.
Exception-Handling Fundamentals  A Java exception is an object that describes an exceptional (that is, error) condition that has occurred in a piece of.
Exceptions Handling Prepared by: Ligemm Mae del Castillo.
1 Exceptions. 2 Syntax Errors, Runtime Errors, and Logic Errors syntax errors, runtime errors, and logic errors You learned that there are three categories.
Lecture10 Exception Handling Jaeki Song. Introduction Categories of errors –Compilation error The rules of language have not been followed –Runtime error.
Exception and Exception Handling. Exception An abnormal event that is likely to happen during program is execution Computer could run out of memory Calling.
ECE122 L23: Exceptions December 6, 2007 ECE 122 Engineering Problem Solving with Java Lecture 24 Exceptions.
Garbage Collection It Is A Way To Destroy The Unused Objects. To do so, we were using free() function in C language and delete() in C++. But, in java it.
Agenda Introduction Errors and Exception Exception Hierarchy Classification of Exceptions Built in Exceptions Exception Handling in Java User defined.
Exception Handling. You learned that there are three categories of errors: syntax errors, runtime errors, and logic errors. Syntax errors arise because.
Chapter 14 – Exception Handling
Chapter 10 – Exception Handling
Why exception handling in C++?
COMPSCI 230 S Programming Techniques
EXCEPTION HANDLING OR ERROR HANDLING.
OBJECT ORIENTED PROGRAMMING
Web Design & Development Lecture 7
Exception Handling in Java
Errors and Exceptions Error Errors are the wrongs that can make a program to go wrong. An error may produce an incorrect output or may terminate the execution.
Java Basics Exception Handling.
Exception Handling.
Chapter 15 – Exception Handling
Presentation transcript:

1 Nested Classes O

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 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(); 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 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 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 O

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” java.lang.ArithmeticException: / by zero at Exc0.main(Exc0.java:4)

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 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 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 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 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 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 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 /* 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 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) { 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 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- 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 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 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 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

 2000 Prentice Hall, Inc. All rights reserved. Outline 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 } public static void throwException() throws Exception 15 { 16 // Throw an exception and catch it in main. 17 try { 18 System.out.println( "Method throwException" ); 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.

 2000 Prentice Hall, Inc. All rights reserved. Outline 30 Program Output Method throwException Finally is always executed Exception handled in main

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 { 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]