10 exceptionsin java

  • 438 views
Uploaded on

 

  • Full Name Full Name Comment goes here.
    Are you sure you want to
    Your message goes here
    Be the first to comment
    Be the first to like this
No Downloads

Views

Total Views
438
On Slideshare
0
From Embeds
0
Number of Embeds
0

Actions

Shares
Downloads
12
Comments
0
Likes
0

Embeds 0

No embeds

Report content

Flagged as inappropriate Flag as inappropriate
Flag as inappropriate

Select your reason for flagging this presentation as inappropriate.

Cancel
    No notes for slide
  • Part of this lecture will be reserved for working through solutions to selected exercises from last week. Notes relating to this do not appear in the slides.

Transcript

  • 1. Exceptions in Java OOSSE - Programming with Java21 Dec 2012 OOSSE - Java Lecture 1
  • 2. Objectives In this lecture, we will • Introduce exception handling • Discuss try, catch and finally • Discuss checked and unchecked exceptions21 Dec 2012 OOSSE - Java Lecture 9 2
  • 3. Exceptions • The Sun Java tutorial defines an exception, an exceptional event, as: “an event that occurs during the execution of a program that disrupts the normal flow of instructions” • Exceptions are generated when something goes wrong – try to divide a number by zero • ArithmeticException – try to access a position past either end of an array • index is negative, or index >= the array length • ArrayIndexOutOfBoundsException – attempt to read data of the wrong type, for example with a Scanner object • InputMismatchException21 Dec 2012 OOSSE - Java Lecture 9 3
  • 4. Exceptions • Some types of exceptions are unpredictable – They may happen on some runs through the program but not others – Unpredictable exceptions do not generate compiler errors • When they do occur, the program terminates and throws an exception • For example: Exception in thread "main" java.lang.ArithmeticException: / by zero at ExceptionEx.main(ExceptionEx.java:6) Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 321 Dec 2012 OOSSE - Java Lecture 9 4
  • 5. Handling Exceptions • A program crash can be avoided by handling the exception • Code that could cause an error is wrapped in a try catch block Scanner kybd = new Scanner(System.in); try { int number = kybd.nextInt(); double price = kybd.nextDouble(); } catch (InputMismatchException ime) { System.out.println("Wrong type of input"); System.out.println(ime.toString()); }21 Dec 2012 OOSSE - Java Lecture 9 5
  • 6. Handling Exceptions • If an exception is generated within the try block then execution immediately jumps to the catch block – the remaining statements in the try block are not executed • The catch block can contain code to deal with the problem and handle the exception – or output a message explaining what went wrong • Regardless of whether an exception occurs, execution continues after the catch block without a crash • There can be more than one catch block – to deal with different types of exception • A finally block can exist after all the catch blocks – executed regardless of whether or not an exception occurs21 Dec 2012 OOSSE - Java Lecture 9 6
  • 7. Handling Exceptions • Code sample: try { int number = kybd.nextInt(); int answer = number / 0; } catch (ArithmeticException ae){ System.out.println(“Divide by zero"); } catch (InputMismatchException ime){ System.out.println("Wrong type of input"); } finally { System.out.println("Finally end up here"); }21 Dec 2012 OOSSE - Java Lecture 9 7
  • 8. Dealing with an Exception Scanner kybd = new Scanner(System.in); int num; boolean done = false; while (!done){ try { System.out.println("Please enter an integer"); num = kybd.nextInt(); done = true; } catch (InputMismatchException e){ String invalidInput = kybd.next(); System.out.println("Wrong input, try again"); } }21 Dec 2012 OOSSE - Java Lecture 9 8
  • 9. Unchecked Exceptions• The examples we have looked at so far are unchecked exceptions – Also known as run-time exceptions• The exceptions are unpredictable – They may or may not occur – They could happen anywhere• The compiler does not insist that they are handled – It is not compulsory to use a try-catch block – If an exception occurs outside of a try-catch block then the program will terminate21 Dec 2012 OOSSE - Java Lecture 9 9
  • 10. Checked Exceptions • Some other exceptions are more predictable – An attempt to open a file that does not exist FileNotFoundException – An attempt to read beyond the end of a file EOFException – Both of these are types of IOException but some other types of exception may also be predictable • Checked exceptions are predictable • If a method call can generate a checked exception you must handle it – otherwise will get a compiler error21 Dec 2012 OOSSE - Java Lecture 9 10
  • 11. Handling File I/O Exceptions • All code that involves opening and accessing a file must be wrapped in a try-catch block try { PrintWriter pw = new PrintWriter("Payroll.txt"); pw.print(name); pw.printf("%6.2f", hourlyPay); // more file-writing code omitted here pw.close(); } catch(IOException e) { System.out.println("Error writing to file"); }21 Dec 2012 OOSSE - Java Lecture 9 11
  • 12. Handling File I/O Exceptions try { Scanner inFile = new Scanner(new File(fileName)); while (inFile.hasNext()) { name = inFile.next(); hourlyPay = inFile.nextDouble(); // more code here to process input } inFile.close(); } catch(IOException e) { System.out.println("Error reading from file"); }21 Dec 2012 OOSSE - Java Lecture 9 12
  • 13. What is an Exception? • The Exception class in Java is the basis for exception handling • The Exception class is a subclass of the Throwable class – java.lang.Throwable • The Exception class defines several methods including: – getMessage() – toString() – printStackTrace() • A method can raise an Exception if something is not right – throw new IOException(“Unable to read data”); • A method can specify that it may throw an Exception – public String myMethod ( ) throws IOException ….21 Dec 2012 OOSSE - Java Lecture 9 13
  • 14. Separating Error-Handling Code from "Regular" Code • readFile { try { • open the file; • determine its size; • allocate that much memory; • read the file into memory; • close the file; } • catch (fileOpenFailed) { doSomething; } catch (sizeDeterminationFailed) { doSomething; } catch (memoryAllocationFailed) { doSomething; } catch (readFailed) { doSomething; } catch (fileCloseFailed) { doSomething; }}21 Dec 2012 OOSSE - Java Lecture 9 14
  • 15. • 2. Propagating Errors Up the Call Stack • method1 { try { • call method2; • } catch (exception e) { • doErrorProcessing; }} • method2 throws exception { • call method3;} • method3 throws exception { • call readFile;} • 3. Grouping and Differentiating Error Types • catch (FileNotFoundException e) { • ...} • catch (IOException e) { ...}21 Dec 2012 OOSSE - Java Lecture 9 15
  • 16. Summary In this lecture we have: • Introduced exception handling • Discussed try, catch and finally • Discussed checked and unchecked exceptions21 Dec 2012 OOSSE - Java Lecture 9 16