exception handling. outline what is an exception how to use exceptions catch ing throw ing extending...

33
Exception Handling

Upload: maria-wilson

Post on 30-Dec-2015

232 views

Category:

Documents


1 download

TRANSCRIPT

Exception Handling

Outline

• What is an Exception• How to use exceptions• catching• throwing• Extending the Exception class• Declaring using the throws clause• GMS_WS exceptions• GridChem exceptions

What is an Exception?

• Exceptions are the customary way in Java to indicate to a calling method that an abnormal condition has occurred.

• In Java, exceptions are objects• Only objects whose classes descend from

Throwable can be thrown.

How do we use Exceptions?

• You can throw objects of your own design or members of the java.lang family.

• Depends on situation– If invalid argument passed to a method ->

java.lang.IllegalArgumentException.– If bad password sent, may want to throw custom exception.

• In GridChem, most situations call for custom exception handling.– Custom exceptions descend from java.lang.Exception family

Example

• Program simulating someone drinking a cup of coffee

Exception hierarchy for coffee sipping.

Example

• If coffee is too cold, throw TooColdException• If coffee is too hot, throw TooHotException• They are exceptions because they are NOT

the normal state of the coffee.

class TemperatureException extends Exception {}class TooColdException extends TemperatureException {}class TooHotException extends TemperatureException {}

Throwing Exceptions

• To throw an exception use the throw keyword• Can only throw objects of type Throwable or one

of its subclasses.

Example Throwing Exceptions

class VirtualPerson { private static final int tooCold = 65; private static final int tooHot = 85;

public void drinkCoffee(CoffeeCup cup) throws TooColdException, TooHotException {

int temperature = cup.getTemperature(); if (temperature <= tooCold) { throw new TooColdException(); } else if (temperature >= tooHot) { throw new TooHotException(); } //... } //...}

Catching Exceptions

• To catch an exception in Java, you write a try block with one or more catch clauses.

• Each catch clause specifies one exception type that it is prepared to handle.

• The try block isolates a section of code and places it under the watch of the assocated catchers.

• If a line of code in the try block throws and exception, the associated catch block will execute.

Example Catching an Exception

class Example1 {public static Logger log =

Logger.getLogger(Example1.class.getName());

public static void main(String[] args) {int temperature = 0;// Create a new coffee cup and set the temperature of// its coffee.CoffeeCup cup = new CoffeeCup();cup.setTemperature(temperature);

try { VirtualPerson vp = new VirtualPerson(); vp.drinkCoffee(cup);} catch (TemperatureException e) { log.error(e);}

}}

Example Catching an Exception

• can have many catch clauses…try {

VirtualPerson vp = new VirtualPerson();

vp.drinkCoffee(cup);

} catch (TooHotException e) {

log.error(“Coffee is too hot!!”);

} catch (TooHotException e) {

log.error(“Coffee is too cold!!”);

} catch (Exception e) {

log.error(“Don’t know why, coffee is just bad!!”);

}

Extending Exception Class

• Providing customized exception classes can – increase the readability of the exception– allow program to take futher corrective action

Extending Exception Class

• Overriding existing constructorsclass UnusualTasteException extends Exception { UnusualTasteException() { } UnusualTasteException(String msg) { super(msg); }}

• First constructor the same• Second allows us to customize the error

message.

Extending Exception Class

class VirtualCafe { public static void serveCustomer(VirtualPerson cust, CoffeeCup cup)

{try {

cust.drinkCoffee(cup); System.out.println("Coffee tastes just right."); } catch (UnusualTasteException e) { System.out.println( "Customer is complaining of an unusual taste."); String s = e.getMessage(); if (s != null) { System.out.println(s); } // Deal with an unhappy customer... } }}

Extending Exception Class

• Sometimes more info may be necessary.• Can inbed other info in exception class and

provide getters and setters.

Extending Exception Class

abstract class TemperatureException extends Exception { private int temperature; // in Celsius public TemperatureException(int temperature) { this.temperature = temperature; } public int getTemperature() { return temperature; }}class TooColdException extends TemperatureException { public TooColdException(int temperature) { super(temperature); }}class TooHotException extends TemperatureException { public TooHotException(int temperature) { super(temperature); }}

Extending Exception Class

• Can now rewrite VirtualPerson class to leverage the improved exception class.

class VirtualPerson { private static final int tooCold = 65; private static final int tooHot = 85;

public void drinkCoffee(CoffeeCup cup) throws TooColdException, TooHotException {

int temperature = cup.getTemperature(); if (temperature <= tooCold) { throw new TooColdException(temperature); } else if (temperature >= tooHot) { throw new TooHotException(temperature); } }}

• Can also use catch clause to take further actions:try { VirtualPerson vp = new VirtualPerson(); vp.drinkCoffee(cup);} catch (TooHotException e) { // wait 30 seconds for coffee to cool while (cup.getTemperature() > CoffeeCup.MAX_TEMP) {

Thread.sleep(30*1000); }

}

Extending Exception Class

• Can now rewrite VirtualPerson class to leverage the improved exception class.

class VirtualPerson { private static final int tooCold = 65; private static final int tooHot = 85;

public void drinkCoffee(CoffeeCup cup) throws TooColdException, TooHotException {

int temperature = cup.getTemperature(); if (temperature <= tooCold) { throw new TooColdException(temperature); } else if (temperature >= tooHot) { throw new TooHotException(temperature); } }}

Extending Exception Class

class VirtualCafe {public static void serveCustomer(VirtualPerson cust,

CoffeeCup cup) {try {

cust.drinkCoffee(cup); System.out.println("Coffee is just right."); } catch (TooColdException e) { int temperature = e.getTemperature(); System.out.println("Coffee temperature is " + temperature + " degrees Celsius."); if (temperature > 55 && temperature <= 65) { System.out.println("Coffee is cooling off."); // Add more hot coffee... } else if (temperature > 0 && temperature <= 55) { System.out.println("Coffee is too cold."); // Give customer a new cup of coffee with the // proper temperature... } else if (temperature <= 0) { System.out.println("Coffee is frozen."); // Deal with an irate customer... } }

Extending Exception Class

catch (TooHotException e) { int temperature = e.getTemperature(); System.out.println("Coffee temperature is " + temperature + " degrees Celsius."); if (temperature >= 85 && temperature < 100) { System.out.println("Coffee is too hot."); // Ask customer to let it cool a few minutes... } else if (temperature >= 100 && temperature < 2000) { System.out.println( "Both coffee and customer are steamed."); // Deal with an irate customer... } else if (temperature >= 2000) { System.out.println( "The coffee is plasma."); // Deal with a very irate customer... } } }}

The throws Clause

• There are two kinds of exceptions in Java:– checked– unchecked

• Only checked exceptions need appear in throws clauses.

• Any checked exceptions that may be thrown in a method must either be caught or declared in the method's throws clause.

• Checked exceptions are so called because both the Java compiler and the Java virtual machine check to make sure this rule is obeyed.

The throws Clause

• Rules of thumb:– Don’t worry about java.lang.Error – Subclass java.lang.RuntimeException for our custom

exceptions.– If the programmer should handled the exception EVERY

time, then declare the exception in a throws clause.– If the exception signals an improper use of the method, then

it should subclass a RuntimeException which would be unchecked.

– If the exception signals an abnormal situation with which the programmer should deal, then it should be checked.

• We need to implement exception handling, not error handling!!

Exceptions in GMS_WS

• Come to the client wrapped as AxisFaults.• Unwrapped in the GMS.java class into an

org.gridchem.client.exception.GMSException.LoginException.javaUserException.javaPermissionException.javaCredentialManagementException.javaProjectException.javaResourceException.javaPreferenceException.javaNotificationException.javaJobSubmissionException.javaJobException.javaInvalidJobRequestException.javaInfrastructureException.javaFileManagementException.javaFileException.java

Login exceptions

VO exceptions

Job Mgmt exceptions

Persistence exceptions

File Mgmt exceptions

Exceptions in GridChem

• Found in the org.gridchem.client.exceptions package.

• Not many right now. Need to be expanded.• Will eventually handle all client-side issues.• Since client depends on service so much, the

client exceptions will probably always be far fewer.