1 / 33

Exception Handling in Java - A Comprehensive Guide

Learn about exceptions in Java, how to use them, catch and throw exceptions, extend the Exception class, declare exceptions using the throws clause, and handle exceptions in GMS_WS and GridChem.

ronniep
Download Presentation

Exception Handling in Java - A Comprehensive Guide

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. Exception Handling

  2. 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

  3. 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.

  4. 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

  5. Example • Program simulating someone drinking a cup of coffee Exception hierarchy for coffee sipping.

  6. 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 { }

  7. Throwing Exceptions • To throw an exception use the throw keyword • Can only throw objects of type Throwable or one of its subclasses.

  8. 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(); } //... } //... }

  9. 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.

  10. 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); } } }

  11. 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!!”); }

  12. Extending Exception Class • Providing customized exception classes can • increase the readability of the exception • allow program to take futher corrective action

  13. Extending Exception Class • Overriding existing constructors class UnusualTasteException extends Exception { UnusualTasteException() { } UnusualTasteException(String msg) { super(msg); } } • First constructor the same • Second allows us to customize the error message.

  14. 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... } } }

  15. Extending Exception Class • Sometimes more info may be necessary. • Can inbed other info in exception class and provide getters and setters.

  16. 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); } }

  17. 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); } } }

  18. 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); } }

  19. 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); } } }

  20. 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... } }

  21. 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... } } } }

  22. 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.

  23. 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!!

  24. 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.java UserException.java PermissionException.java CredentialManagementException.java ProjectException.java ResourceException.java PreferenceException.java NotificationException.java JobSubmissionException.java JobException.java InvalidJobRequestException.java InfrastructureException.java FileManagementException.java FileException.java Login exceptions VO exceptions Job Mgmt exceptions Persistence exceptions File Mgmt exceptions

  25. 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.

More Related