My other sites

Latest News

New Summer Look :)










Exceptions, Packages, Modifiers

  Java Exceptions and Errors

Exceptions

Exception Handling Example

Creating Exception Types

Java's Packages

Accessing Classes in Packages

Packages and the CLASSPATH

Access Modifiers

Quiz

Exercises
 


Java Exceptions and Errors


-There is a trade-off between correctness and clarity:

- Correctness, checking for errors

- Clarity, a clear and readable basic flow of the code

- Exceptions are a clean way to manage abnormal states

- Exception : mild error which you can handle

- Error : serious error -> termination

- The idea is to signal exceptions to the current running process announcing that a problem has occurred

- An exception is thrown and then caught


Exceptions

An exception arises in code at runtime

Two subclasses of Throwable:

- Exception

- Error

Un-handled exceptions -> Error (Catastrophic failure)
 

//try - catch - finally Statement
try {
   // block of code that may throw an exception.
   [ return; ]
} 
catch (ExceptionType1 e) { 
   // Exception handler for type1
} 
catch (ExceptionType2 e) {
   // Exception handler for type2
   throw(e) // re-throw e Exception
}

finally {
   // clean-up code
}

 

Exception Handling Example

public class ExceptionExample {
   public static void main (String[] argv) {
      int [] numArray; // declaration 
      numArray = new int[10]; // creation
      try {
         for (int x=0; x<numArray.length +1; x++) {
           numArray[x] = x * 2;
           System.out.print(numArray[x] + ":");
         }
      } 
      catch (ArrayIndexOutOfBoundsException ex) {
         System.out.println("Array Exception caught!!");
      }
      finally {
         System.out.println("Reached finally clause");
      } 
   } 
}


Creating Exception Types


public class InvalidPasswordException extends Exception {
  InvalidPasswordException(String msg){
    super(msg);
  }
}
public void loginUser(User usr) throws InvalidPasswordException { //Now the caller of loginUser is forced to provide a way to //handle the possible exception
String password = getPassword(usr); if (!evaluate(password)) throw new InvalidPasswordException("Invalid password"); else startlogin(usr); } }

 

Java's Packages

Package is a:

- Path to a directory containing a set of classes,

- Name space, and

- Naming mechanism


Accessing Classes in Packages


There are three ways to access classes in other packages:

1. Write the full name of the class:


class ExitFrame extends java.awt.Frame { ... }

2. Import a specific class:

import java.awt.Frame;
class ExitFrame extends Frame { ... }

3. Import all exported classes from a package:

import java.awt.*;
class ExitFrame extends Frame { ... }


Packages and the CLASSPATH


- CLASSPATH is a environmental variable that holds directory paths to java classes

- A class can belong to a package only if its source code declared membership with the package statement

- To create and execute a class file belonging to a package :

a. Declare package membership on the source code's 1st line

b. Put the class file in an appropriate directory
- i.e. if package cm.cmd.tool; then ../cm/cmd/tool/

c. Make sure that CLASSPATH knows the path to the classes in need
- i.e. if package cm.cmd.tool; then ../cm/cmd/tool/


Access Modifiers


For Methods and Fields :

Qualifier
Scope
private
class
private protected
class + subclass
< none >
class + package
protected
class + subclass + package
public
global


For Classes:

Qualifier
Scope
< none >
package
public
all

 

Quiz


1. Class B can access a method of a class A which resides in a different package. Class A is public and the method is protected. What is the relationship between these two classes?

2. Consider the diagram below. Which of the following statements are true and which are false?


1. import A.*; Imports all the classes in package A and in package B and C
2. import A.A*; Imports all the classes in package A that start with the letter A
3. import A; Imports all the classes of package A
4. import B.B; Imports class B from package B
5. import *; Imports all the packages described by the CLASSPATH

3. What is the output of the following program?

    public class TestException {
       public static void main(String[] args) {
	   int[] intArray= new int[10];
	   boolean result = fillArray(intArray);
	   System.out.println("Result: " + result);	
       }
	public static boolean fillArray(int[] intArray) {
	   try {
	     intArray[0] = 99;		
	     return true;
	  } catch(Exception e) {
	     System.out.println("Exc. accessing the array!");
	  }
	  finally {
	     return false;
	  }
       }
}

 

Exercises


1. Write three classes : Rectangle, Circle and Triangle, all inheriting from an abstract class aShape. Add methods to calculate the surface of those shapes

Use the Shape hierarchy to instantiate five shapes and put them into an array. Then calculate the average surface area of those five shapes

Find how to use the Random class to generate random values to initialise the shape objects

Put the classes into a package call shapes and import them in your main app class..

 


previous, contents, next