Presentation is loading. Please wait.

Presentation is loading. Please wait.

Winter 2006CISC121 - Prof. McLeod1 Last Time Reviewed class structure: –attributes –methods –(inner classes) Looked at the effects of the modifiers: –public.

Similar presentations


Presentation on theme: "Winter 2006CISC121 - Prof. McLeod1 Last Time Reviewed class structure: –attributes –methods –(inner classes) Looked at the effects of the modifiers: –public."— Presentation transcript:

1 Winter 2006CISC121 - Prof. McLeod1 Last Time Reviewed class structure: –attributes –methods –(inner classes) Looked at the effects of the modifiers: –public | private –static

2 Winter 2006CISC121 - Prof. McLeod2 Assignment 1 & “Stuff” If you are having problems with assn1, have a look at the solution to Lab 3. Class rep (for USAT’s): –please contact Mireille Gomes at 3mmg2@qlink.queensu.ca.

3 Winter 2006CISC121 - Prof. McLeod3 Today Why write Methods? Passing parameters by value or by reference. Exceptions.

4 Winter 2006CISC121 - Prof. McLeod4 Method Examples public void printHello() { System.out.println(“Hello”); } // end printHello public void printHelloName(String yourName) { System.out.println(“Hello “ + yourName); } // end printHelloName public void printAvg(int a, int b) { System.out.println((a + b) / 2.0); } // end printAvg

5 Winter 2006CISC121 - Prof. McLeod5 Method Examples - Cont. public double average(double a, double b) { return (a + b) / 2; } // end average public int lowest(int a, int b) { if (a <= b) return a; else return b; } // end lowest

6 Winter 2006CISC121 - Prof. McLeod6 Methods - Cont. Why use methods? Modular design. Avoids repetitious code. Independent testing of sub-tasks. Reusable code. –Design and test a method once, and re-use it whenever you need to solve a similar problem. Isolation from unintended side effects. –The only variables from the caller that can be seen from a method are those in the parameter list.

7 Winter 2006CISC121 - Prof. McLeod7 Methods - Cont. Start thinking of your program as a collection of methods, where the main method only acts to call the other methods. The use of modular design techniques with methods is called “encapsulation”.

8 Winter 2006CISC121 - Prof. McLeod8 Methods – Some Advice… When designing method operations, make sure a method only does one “thing”, do not combine operations (except in main ). Concentrate on coding the individual methods, one at a time, when you write a program. If you have thought out the “code-level interface” between the methods, then the methods will be completely independent of each other. Try to minimize the size of the main method, if possible. However, if the main method is going to be responsible for screen I/O then more code may be necessary.

9 Winter 2006CISC121 - Prof. McLeod9 Passing Parameters by Reference See PassingDemo.java –Has a method with two parameters - an array and an int - which one(s) will stay changed? –Instead of going element by element, if you re-assign the array to another array within the method, what happens?

10 Winter 2006CISC121 - Prof. McLeod10 Passing Arrays by Reference Summary of PassingDemo.java: –Primitive types are passed by value. –Only element by element changes in arrays will “stick”. –Re-assigning the array to a pointer that has local scope in a method will not “stick”.

11 Winter 2006CISC121 - Prof. McLeod11 Exceptions How can a method indicate that it is unable to return what it is supposed to return? How can a method deliver details about the error condition? How can you prevent the instantiation of an Object? The limitation of only returning a single “thing” means that you either designate error values for the “thing” or you have some other way to return the indication of an error.

12 Winter 2006CISC121 - Prof. McLeod12 Exceptions - Cont. The designers of Java followed conventions used by many other OOP languages, they allowed for another way to return something. Exceptions are objects (big surprise!). When an error condition is encountered, a method can throw an instance of a pre-defined exception object.

13 Winter 2006CISC121 - Prof. McLeod13 Exceptions - Cont. How does an Exception Object contain information about the error condition? –The name of the Object: IOException NumberFormatException FileNotFoundException ArrayIndexOutOfBoundsException … So, the method must throw a relevant exception object. Turns out that exceptions can also carry a String message.

14 Winter 2006CISC121 - Prof. McLeod14 Exceptions – Cont. An exception is just a: The exception itself cannot do anything about the problem.

15 Winter 2006CISC121 - Prof. McLeod15 Exceptions – Cont. The act of throwing an exception immediately stops the method that is throwing the exception (like a return statement…). Execution control is passed back to the invoking method, that was possibly waiting for a return value! No return value is forthcoming!

16 Winter 2006CISC121 - Prof. McLeod16 Exceptions - Cont. Instead the invoking method must be prepared to catch the exception. This is done with a “try/catch” block:

17 Winter 2006CISC121 - Prof. McLeod17 Exceptions – Cont. Syntax of a “try-catch block”: try { // block of statements that might // generate an exception } catch (exception_type identifer) { // block of statements }[ catch (exception_type identifer) { // block of statements … }][ finally { // block of statements }]

18 Winter 2006CISC121 - Prof. McLeod18 Exceptions – Cont. You must have at least one “catch block” after the “try block” (otherwise the try block would be useless!) You can have many catch blocks, one for each exception you are trying to catch. The code in the “finally” block is always executed, whether an exception is thrown, caught, or not.

19 Winter 2006CISC121 - Prof. McLeod19 Exceptions - Cont. A method can throw more than one kind of exception. Why would you want to do this? You can also include more than one line of code that can throw an exception inside a try block. Why would you not want to do this?

20 Winter 2006CISC121 - Prof. McLeod20 Exceptions – Cont. We have had to use try/catch blocks with file I/O - the nasty compiler forces us to do so! We can’t ignore the possibility of certain methods throwing exceptions: FileReader fileIn = null; try{ fileIn = new FileReader(filename); } catch (FileNotFoundException e) { System.out.println("Cannot open file!"); System.exit(0); } Scanner fileInput = new Scanner(fileIn);

21 Winter 2006CISC121 - Prof. McLeod21 Exceptions – Cont. Note that you can use the code e.getMessage() to get an error description string from the exception inside the catch clause. You can supply the message to the Exception constructor when you throw one (later). When used with some exceptions, the e.getMessage() method just returns null, as they do not contain a message.

22 Winter 2006CISC121 - Prof. McLeod22 Exceptions – Cont. What exception classes to use? –The pre-compiler in eclipse will tell you which exceptions you have to catch. –Observe the error at runtime, and note the exception name. –Look at the Exception class hierarchy in the API documentation. –A more abstract exception class will catch more exceptions with a single “catch” clause, but the more abstract the error condition, the harder it will be to report and/or deal with on concrete terms.

23 Winter 2006CISC121 - Prof. McLeod23 Exceptions – Cont. If an exception is thrown and not caught? –Exception was thrown outside of a try-catch block, or –Was inside of a try block, but no catch statement matched the exception: Now the exception is “propogated” back to the calling method. If the calling method called the original method in a try block, then the calling method tries to catch the exception.

24 Winter 2006CISC121 - Prof. McLeod24 Exceptions – Cont. Otherwise the exception just keeps moving up the “call chain”. If not caught, eventually it will reach the main method. If main does not catch the exception, the program terminates (“crashes!”) and a cryptic method is sent to the screen, identifying the exception.

25 Winter 2006CISC121 - Prof. McLeod25 Defining Exceptions You can throw an exception already defined in java, but: Most of the time you will want to throw your own exception objects. Why not? It’s easy! See the next slide for the definition of an Exception object.

26 Winter 2006CISC121 - Prof. McLeod26 Defining Exceptions, Cont. public class IllegalStudentInfoException extends Exception { public IllegalStudentInfoException (String message) { super(message); } public IllegalStudentInfoException () { super("Illegal data supplied to constructor."); } } // end IllegalStudentInfoException

27 Winter 2006CISC121 - Prof. McLeod27 Defining Exceptions, Cont. Inside a method that detects this condition: throw new IllegalStudentInfoException("Illegal student number: " + number); At the end of the method header that contains the above line of code: … throws IllegalStudentInfoException {

28 Winter 2006CISC121 - Prof. McLeod28 Defining Exceptions, Cont. This example contains a few Java syntax elements that we have not yet discussed: –extends –super –throw –throws We may not discuss the exact meaning and usage of these keywords – but you can still write your own exceptions by following the provided pattern!


Download ppt "Winter 2006CISC121 - Prof. McLeod1 Last Time Reviewed class structure: –attributes –methods –(inner classes) Looked at the effects of the modifiers: –public."

Similar presentations


Ads by Google