1 / 24

Advanced Programming in Java

Advanced Programming in Java. Sadegh Aliakbary Sharif University of Technology Fall 2010. Agenda. Exception Handling. Watch This Method. public static Integer getYear (String day){ String yearString = day.substring (0,4); int year = Integer. parseInt ( yearString );

ordell
Download Presentation

Advanced Programming in Java

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. Advanced Programming in Java SadeghAliakbary Sharif University of Technology Fall 2010

  2. Agenda • Exception Handling Sharif University of Technology

  3. Watch This Method publicstatic Integer getYear(String day){ String yearString = day.substring(0,4); int year = Integer.parseInt(yearString); return year; } publicstaticvoid main(String[] args) { String day = "2010/11/29"; Integer year = getYear(day); System.out.println(year); } Sharif University of Technology

  4. Exceptions • What is wrong with it? • What if day parameter is not a day representation? • day = “salam!” • What if day parameter is malformed? • Day = “29 Nov 2010” • What if day parameter is null? • This occasions are called Exception Sharif University of Technology

  5. Handling Exceptions • What to do with exceptions? • Exit the program • Printing the error on console • Returning a special value • e.g. -1 Sharif University of Technology

  6. Important Note • Sometimes the method can’t handle the exception effectively • What should a method do when an exception occurs? • Exit the program? • Suppose you are in a desktop application • Excel, Word, a game, … • Print on console? • edu site • A game Sharif University of Technology

  7. Returning a Special Value • We can return a special value to report an exception • E.g. • return null; • return -1; • return 0; • return “”; • Why not? Sharif University of Technology

  8. Why not? • There is no return value • Return type : void • There is no special value • There are many exceptions • Ambiguity • Need for documentation • Combination of program code and exception code Sharif University of Technology

  9. There is no special value publicstaticint minimum(int[] nums ){ int m = Integer.MAX_VALUE; for (inti : nums) { m = Math.min(m, i); } return m; } int[] array = {1,2,-1}; intminimumFound = minimum(array); Sharif University of Technology

  10. Exception Handling • Exception Handling is a framework for handling exceptions • It simplifies code • Separates business code and exception code Sharif University of Technology

  11. What is an Exception? • Exceptional event • Error that occurs during runtime • Cause normal program flow to be disrupted • Examples • ? • Divide by zero errors • Accessing the elements of an array beyond its range • Invalid input • Hard disk crash • Opening a non-existent file • Heap memory exhausted Sharif University of Technology

  12. Default Exception Handling • Provided by Java runtime • Prints out exception description • Prints the stack trace • Hierarchy of methods where the exception occurred • Causes the program to terminate Sharif University of Technology

  13. Example classDivByZero { publicstaticvoid main(String a[]) { System.out.println(3/0); } } Exception in thread "main" java.lang.ArithmeticException: / by zero at exception.Test2.main(Test2.java:19) Sharif University of Technology

  14. What Happens When an Exception Occurs? • When an exception occurs within a method • The method creates an exception object • And hands it off to the runtime system • This job is called “throwing an exception” • Exception object contains • information about the error • its type • the state of the program when the error occurred Sharif University of Technology

  15. What Happens When an Exception Occurs (2)? • The runtime system searches the call stack • For a method that contains an exception handler • When an appropriate handler is found • The runtime system passes the exception to the handler • The exception handler catches the exception • What if the runtime system can not find an exception handler? • Uses the default exception handler Sharif University of Technology

  16. Sharif University of Technology

  17. Sharif University of Technology

  18. Exception Handling in Java publicstatic Integer getYear(String day) { String yearString = day.substring(0, 4); int year = Integer.parseInt(yearString); return year; } publicstaticvoid main(String[] args) { Scanner scanner = new Scanner(System.in); System.out.print("Enter a well-formed date: "); String date = scanner.next(); Integer year = getYear(date); System.out.println(year); } Sharif University of Technology

  19. getYear() publicstatic Integer getYear(String day) throws Exception { if (day == null) thrownew Exception("null value"); if (day.length() == 0) thrownew Exception("empty value"); if (!matchesDateFormat(day)) thrownew Exception("malformed value"); String yearString = day.substring(0, 4); int year = Integer.parseInt(yearString); return year; } privatestaticbooleanmatchesDateFormat(String input) { returninput.matches("\\d\\d\\d\\d/\\d\\d/\\d\\d"); } Sharif University of Technology

  20. main() publicstaticvoid main(String[] args) { Scanner scanner = new Scanner(System.in); boolean ok = false; while (ok == false) { System.out.print("Enter a well-formed date: "); String date = scanner.next(); try { Integer year = getYear(date); System.out.println(year); ok = true; } catch (Exception e) { System.out.println(e.getMessage()); } } } Sharif University of Technology

  21. Exception Handling Keywords • throw • throws a new exception • throws • Declares exception throw • try • Start a block with exception handling • catch • Catch the exception Sharif University of Technology

  22. Benefits of Exception Handling Framework • Separating Error-Handling code from “regular” business logic code • Propagating errors up the call stack • Grouping and differentiating error types Sharif University of Technology

  23. Sharif University of Technology

  24. References http://www.javapassion.com/javase/javaexceptions.pdf Sharif University of Technology

More Related