Survey
* Your assessment is very important for improving the workof artificial intelligence, which forms the content of this project
* Your assessment is very important for improving the workof artificial intelligence, which forms the content of this project
KING FAHD UNIVERSITY OF PETROLEUM & MINERALS Information and Computer Science Department ICS-201 Introduction to Computer Science Lab 06: Exception Handling Mechanisms and Inner Classes Objectives: In this lab, the following topics will be covered 1. 2. 3. 4. Exception Handling User Defined Exceptions Inner Classes Examples & Exercises for practice 1- Exception Handling An exception is an unusual condition. It may or may not be an error. Java provides exception handling to deal with exceptional conditions. Exceptions may be handled as follows: Whenever an exception is generated, either it should be handled using an appropriate try … catch block, or it must be thrown. For example, if the user enters an invalid input, the following mechanism may be used to handle an exception: Scanner key = new Scanner(System.in); System.out.println(“Enter an integer: “); try { int val = key.nextInt(); } catch(InputMismatchException e) { System.out.println(“Invalid Input”); } The ‘throw’ clause may be used to generate an exception for cases which are not handled by built-in java exceptions. Exercise 1: Write a java program which repeatedly prompts the user for a double precision number until the user enters correct input. Your output should be as follows: Enter a double precision number> ICS-201 Invalid Input. Please try again. Enter a double precision number> 43o Invalid Input. Please try again Enter a double precision number> 43.0 You entered 43.0 2 – User Defined Exceptions & Propagating Exceptions Java provides several different types of Exceptions. Some of these exceptions are checked, which means they must be caught or declared to be thrown. Examples of checked exceptions are IOException, etc. An unchecked exception is optional. You may choose to handle it or ignore it. An example of an unchecked exception is ArrayIndexOutOfBoundsException. Consider the following user-defined exception class IllegalValuesException extends Exception { public IllegalValuesException(String message) { super(message); } public IllegalValuesException() { super(“Illegal Values”); } } Now consider the following program: Example: import java.util.*; class IllegalValuesException extends Exception { public IllegalValuesException(String message) { super(message); } public IllegalValuesException() { super("Illegal Values"); } } class Triangle { private double a, b, c; public Triangle(double x, double y, double z) throws IllegalValuesException { if(x+y > z && y+z > x && x+z > y) { a = x; b = y; c = z; } else throw new IllegalValuesException("Error: Values "+x+", "+y+", "+z+ " do not make a valid triangle"); } public double area() { double s = this.perimeter()/2.0; return Math.sqrt(s*(s - a)*(s - b)*(s - c)); } public double perimeter() { return a + b + c; } } public class TriangleTest { public static void main(String[] args) { Triangle[] t = new Triangle[2]; try { t[0] = new Triangle(6, 6, 6); t[1] = new Triangle(1, 4, 1); } catch(IllegalValuesException e1) { System.out.println(e1.getMessage()); } try { Scanner s = new Scanner(System.in); System.out.println("Enter an integer (from 1 to 2): "); int val = s.nextInt(); System.out.println("Triangle: Area:" + t[val - 1].area() + " Perimeter: " +t[val - 1].perimeter()); } catch(InputMismatchException e2) { System.out.println("You entered a non-integer!"); } catch(ArrayIndexOutOfBoundsException e3) { System.out.println("You entered a value which is not in the range 1-2"); } catch(NullPointerException e4) { System.out.println("Sorry this triangle does not exist since it had illegal values"); } } } Observe that we could have bundled all exceptions into one exception as follows (not a good programming practice): try { } catch(Exception e) { … //exception handling code } Exercise 2: Add one more triangle to the above main program by making appropriate changes (e.g. change the size of the Triangle array to 3, define t[2] = new Triangle(4, 4, 4), etc.) Does your program work for this triangle? Modify the exception handling mechanism to make this program work. Exercise 3: Write a program in java that does the following: 1. It prompts the user for an integer 2. It calculates the factorial of that integer in another method (public double factorial(int n)). Observe that the factorial of an integer n is given by: factorial(n) = n (n – 1)(n – 2)… 3. 2. 1 For example factorial(4) = 4.3.2.1 = 24 By definition, factorial(0) = 1. 3. The resulting factorial is printed in the main method: A sample output session is: Enter an integer: 5 The factorial of 5 is 120. 4. Several exceptions could be thrown in this process. (a) if the user enters a non-integer (for example 3.5) (b) if the user enters a negative integer (factorials of negative integers are not defined) (c) if the user enters an integer whose factorial is too large to fit in the range int. (Typically java’s primitive type int cannot calculate factorial(14) or higher correctly). 5. Use java’s built-in exceptions and/or user defined exceptions to catch an exception and print an appropriate message for each one of the above cases separately. Make sure the program repeatedly asks for user input until the user enters a valid input. The program then prints the factorial of the input. A sample output session is: Enter an integer: 3.5 Exception: You entered a non-integer Enter an integer: -3 Exception: You entered a negative integer Enter an integer: 20 Exception: factorial(20) is too large for int data type Enter an integer: 7 The factorial of 7 is 5040 Process Completed. 3- Inner classes: Ordinary classes that we have covered so far are called top-level classes. The access modifiers allowed for them are public and default only. Nested classes are classes defined inside other classes. These nested classes can be static or non static. Static nested classes are called static inner classes or top-level nested classes. A non static nested class is called an inner class. Static and non static inner classes can have all four access modifiers i.e. public, protected, default, and private. Static inner classes are nested for organizational convenience. The additional thing added by nesting is the name and access level of the class. Static inner classes cannot access non static members of the enclosing class. Non static inner classes cannot have static members. Each instance (object) of the inner class is linked to an object of the outer class. The non static inner class can access all members of the outer class (variables and methods) even if they are private. You can access the members of the inner classes from the enclosing class, but after an object from the corresponding inner class is made. A local class is a class declared within a block of code. A local class is visible and usable within the block of code in which it is defined. A local class can access all members of the enclosing class even if they are private. In addition, it can access any final local variable or method parameters defined within its scope. Local classes cannot have access modifiers, and static members. If we are defining a local class and making only one object from it, then it can be converted into an anonymous class. Thus, an anonymous class is a local class with no name. Since an anonymous class has no name, you can not declare a variable to be of that type. For this reason, anonymous classes must either be a subclass of another class or implement an interface. An anonymous class is always defined in a statement. Example: This program creates a square object alongwith a pair of coordinates in the interior of the square and then draws the square with the coordinates of the point. class Square { //All data is private private double side, x, y; public Square(double side, double x, double y) { this.side = side; this.x = x; this.y = y; if((x >= side || y >= side) || (x <= 1 || y <= 1)) { System.out.println("Invalid X and Y Coordinates"); System.exit(0); } } //inner class class Drawer { public Drawer() { System.out.println("Drawer Initialized"); System.out.println("Drawing with side = " +side+ " x = " +x+ " y = " +y); } public void draw() { //Here row = 1 for(int col = 1; col <= side; col++) System.out.print("O"); System.out.println(); for(int row = 2; row <= side - 1; row++) { System.out.print("O"); for(int col = 2; col <= side - 1; col++) if(x == col && y == row) System.out.print("X"); else System.out.print(" "); System.out.println("O"); } //This is the last row for(int col = 1; col <= side; col++) System.out.print("O"); } } } public class DrawTest { public static void main(String[] args) { Square s1 = new Square(10, 5, 9); Square.Drawer d1 = s1.new Drawer(); d1.draw(); } } Exercise 4: Modify the above example so that it works for a rectangle, i.e. create a rectangle with specified width and height and then draw it alongwith the coordinates of a point x and y in the interior of the rectangle.