SlideShare uma empresa Scribd logo
1 de 16
Exceptions in Java


              OOSSE - Programming with Java




21 Dec 2012            OOSSE - Java Lecture   1
Objectives
  In this lecture, we will
  • Introduce exception handling
  • Discuss try, catch and finally
  • Discuss checked and unchecked exceptions




21 Dec 2012            OOSSE - Java Lecture 9   2
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
              • InputMismatchException


21 Dec 2012                       OOSSE - Java Lecture 9                  3
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: 3


21 Dec 2012                OOSSE - Java Lecture 9                  4
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
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 occurs


21 Dec 2012                   OOSSE - Java Lecture 9                   6
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
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
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 terminate




21 Dec 2012                OOSSE - Java Lecture 9                     9
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 error




21 Dec 2012                   OOSSE - Java Lecture 9              10
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
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
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
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
•   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
Summary
  In this lecture we have:
  • Introduced exception handling
  • Discussed try, catch and finally
  • Discussed checked and unchecked exceptions




21 Dec 2012            OOSSE - Java Lecture 9    16

Mais conteúdo relacionado

Mais procurados

Generic Attack Detection - ph-Neutral 0x7d8
Generic Attack Detection - ph-Neutral 0x7d8Generic Attack Detection - ph-Neutral 0x7d8
Generic Attack Detection - ph-Neutral 0x7d8
Mario Heiderich
 
J unit스터디슬라이드
J unit스터디슬라이드J unit스터디슬라이드
J unit스터디슬라이드
ksain
 

Mais procurados (11)

Pi j4.2 software-reliability
Pi j4.2 software-reliabilityPi j4.2 software-reliability
Pi j4.2 software-reliability
 
Java Heap Dump Analysis Primer
Java Heap Dump Analysis PrimerJava Heap Dump Analysis Primer
Java Heap Dump Analysis Primer
 
Exception
ExceptionException
Exception
 
Exceptions and errors in Java
Exceptions and errors in JavaExceptions and errors in Java
Exceptions and errors in Java
 
Generic Attack Detection - ph-Neutral 0x7d8
Generic Attack Detection - ph-Neutral 0x7d8Generic Attack Detection - ph-Neutral 0x7d8
Generic Attack Detection - ph-Neutral 0x7d8
 
J unit스터디슬라이드
J unit스터디슬라이드J unit스터디슬라이드
J unit스터디슬라이드
 
SQL Injection: Amplifying Data Leakeage
SQL Injection: Amplifying Data LeakeageSQL Injection: Amplifying Data Leakeage
SQL Injection: Amplifying Data Leakeage
 
xUnit Style Database Testing
xUnit Style Database TestingxUnit Style Database Testing
xUnit Style Database Testing
 
Presentation on-exception-handling
Presentation on-exception-handlingPresentation on-exception-handling
Presentation on-exception-handling
 
Java exception
Java exception Java exception
Java exception
 
Exception Handling
Exception HandlingException Handling
Exception Handling
 

Destaque

02 introductionto java
02 introductionto java02 introductionto java
02 introductionto java
APU
 
13 gui development
13 gui development13 gui development
13 gui development
APU
 
Design patterns structuralpatterns(thedecoratorpattern)
Design patterns structuralpatterns(thedecoratorpattern)Design patterns structuralpatterns(thedecoratorpattern)
Design patterns structuralpatterns(thedecoratorpattern)
APU
 
08 aggregation and collection classes
08  aggregation and collection classes08  aggregation and collection classes
08 aggregation and collection classes
APU
 
5. state diagrams
5. state diagrams5. state diagrams
5. state diagrams
APU
 
4. class diagrams using uml
4. class diagrams using uml4. class diagrams using uml
4. class diagrams using uml
APU
 
8. design patterns
8. design patterns8. design patterns
8. design patterns
APU
 
01 introduction to_module
01 introduction to_module01 introduction to_module
01 introduction to_module
APU
 
9. oo languages
9. oo languages9. oo languages
9. oo languages
APU
 
12 multi-threading
12 multi-threading12 multi-threading
12 multi-threading
APU
 
6. activity diagrams
6. activity diagrams6. activity diagrams
6. activity diagrams
APU
 
01 introduction to_module
01 introduction to_module01 introduction to_module
01 introduction to_module
APU
 
09 abstract classesandinterfaces
09 abstract classesandinterfaces09 abstract classesandinterfaces
09 abstract classesandinterfaces
APU
 
4.class diagramsusinguml
4.class diagramsusinguml4.class diagramsusinguml
4.class diagramsusinguml
APU
 
7. sequence and collaboration diagrams
7. sequence and collaboration diagrams7. sequence and collaboration diagrams
7. sequence and collaboration diagrams
APU
 
3. use cases
3. use cases3. use cases
3. use cases
APU
 
Usecase diagram railway reservation system
Usecase diagram railway reservation systemUsecase diagram railway reservation system
Usecase diagram railway reservation system
muthumeenakshim
 
5.state diagrams
5.state diagrams5.state diagrams
5.state diagrams
APU
 
14 file handling
14 file handling14 file handling
14 file handling
APU
 

Destaque (19)

02 introductionto java
02 introductionto java02 introductionto java
02 introductionto java
 
13 gui development
13 gui development13 gui development
13 gui development
 
Design patterns structuralpatterns(thedecoratorpattern)
Design patterns structuralpatterns(thedecoratorpattern)Design patterns structuralpatterns(thedecoratorpattern)
Design patterns structuralpatterns(thedecoratorpattern)
 
08 aggregation and collection classes
08  aggregation and collection classes08  aggregation and collection classes
08 aggregation and collection classes
 
5. state diagrams
5. state diagrams5. state diagrams
5. state diagrams
 
4. class diagrams using uml
4. class diagrams using uml4. class diagrams using uml
4. class diagrams using uml
 
8. design patterns
8. design patterns8. design patterns
8. design patterns
 
01 introduction to_module
01 introduction to_module01 introduction to_module
01 introduction to_module
 
9. oo languages
9. oo languages9. oo languages
9. oo languages
 
12 multi-threading
12 multi-threading12 multi-threading
12 multi-threading
 
6. activity diagrams
6. activity diagrams6. activity diagrams
6. activity diagrams
 
01 introduction to_module
01 introduction to_module01 introduction to_module
01 introduction to_module
 
09 abstract classesandinterfaces
09 abstract classesandinterfaces09 abstract classesandinterfaces
09 abstract classesandinterfaces
 
4.class diagramsusinguml
4.class diagramsusinguml4.class diagramsusinguml
4.class diagramsusinguml
 
7. sequence and collaboration diagrams
7. sequence and collaboration diagrams7. sequence and collaboration diagrams
7. sequence and collaboration diagrams
 
3. use cases
3. use cases3. use cases
3. use cases
 
Usecase diagram railway reservation system
Usecase diagram railway reservation systemUsecase diagram railway reservation system
Usecase diagram railway reservation system
 
5.state diagrams
5.state diagrams5.state diagrams
5.state diagrams
 
14 file handling
14 file handling14 file handling
14 file handling
 

Semelhante a 10 exceptionsin java

Cso gaddis java_chapter12
Cso gaddis java_chapter12Cso gaddis java_chapter12
Cso gaddis java_chapter12
mlrbrown
 
Exception handling
Exception handlingException handling
Exception handling
Ravi Sharda
 
exceptionvdffhhhccvvvv-handling-in-java.ppt
exceptionvdffhhhccvvvv-handling-in-java.pptexceptionvdffhhhccvvvv-handling-in-java.ppt
exceptionvdffhhhccvvvv-handling-in-java.ppt
yjrtytyuu
 
Ch-1_5.pdf this is java tutorials for all
Ch-1_5.pdf this is java tutorials for allCh-1_5.pdf this is java tutorials for all
Ch-1_5.pdf this is java tutorials for all
HayomeTakele
 

Semelhante a 10 exceptionsin java (20)

Java exception handling ppt
Java exception handling pptJava exception handling ppt
Java exception handling ppt
 
06 exceptions
06 exceptions06 exceptions
06 exceptions
 
Exceptions handling in java
Exceptions handling in javaExceptions handling in java
Exceptions handling in java
 
Cso gaddis java_chapter12
Cso gaddis java_chapter12Cso gaddis java_chapter12
Cso gaddis java_chapter12
 
exception-handling-in-java.ppt
exception-handling-in-java.pptexception-handling-in-java.ppt
exception-handling-in-java.ppt
 
Exception handling in java
Exception handling in javaException handling in java
Exception handling in java
 
Best Practices in Exception Handling
Best Practices in Exception HandlingBest Practices in Exception Handling
Best Practices in Exception Handling
 
exception-handling-in-java.ppt unit 2
exception-handling-in-java.ppt unit 2exception-handling-in-java.ppt unit 2
exception-handling-in-java.ppt unit 2
 
Exception handling
Exception handlingException handling
Exception handling
 
exceptionvdffhhhccvvvv-handling-in-java.ppt
exceptionvdffhhhccvvvv-handling-in-java.pptexceptionvdffhhhccvvvv-handling-in-java.ppt
exceptionvdffhhhccvvvv-handling-in-java.ppt
 
Ch-1_5.pdf this is java tutorials for all
Ch-1_5.pdf this is java tutorials for allCh-1_5.pdf this is java tutorials for all
Ch-1_5.pdf this is java tutorials for all
 
Adv java unit 1 M.Sc CS.pdf
Adv java unit 1 M.Sc CS.pdfAdv java unit 1 M.Sc CS.pdf
Adv java unit 1 M.Sc CS.pdf
 
Exceptions overview
Exceptions overviewExceptions overview
Exceptions overview
 
Exception handling in java
Exception handling in javaException handling in java
Exception handling in java
 
Exception Handling.ppt
 Exception Handling.ppt Exception Handling.ppt
Exception Handling.ppt
 
Exception handling in java
Exception handling in javaException handling in java
Exception handling in java
 
JAVA UNIT 2
JAVA UNIT 2JAVA UNIT 2
JAVA UNIT 2
 
Unit 5 Java
Unit 5 JavaUnit 5 Java
Unit 5 Java
 
Chapter 5 Exception Handling (1).pdf
Chapter 5 Exception Handling (1).pdfChapter 5 Exception Handling (1).pdf
Chapter 5 Exception Handling (1).pdf
 
Java 9
Java 9Java 9
Java 9
 

Mais de APU

. 1. introduction to object orientation
. 1. introduction to object orientation. 1. introduction to object orientation
. 1. introduction to object orientation
APU
 
. 01 introduction_to_module
. 01 introduction_to_module. 01 introduction_to_module
. 01 introduction_to_module
APU
 
. 9. oo languages
. 9. oo languages. 9. oo languages
. 9. oo languages
APU
 
. 8. design patterns
. 8. design patterns. 8. design patterns
. 8. design patterns
APU
 
. 5. state diagrams
. 5. state diagrams. 5. state diagrams
. 5. state diagrams
APU
 
. 4. class diagrams using uml
. 4. class diagrams using uml. 4. class diagrams using uml
. 4. class diagrams using uml
APU
 
. 2. introduction to uml
. 2. introduction to uml. 2. introduction to uml
. 2. introduction to uml
APU
 
. 01 introduction_to_module
. 01 introduction_to_module. 01 introduction_to_module
. 01 introduction_to_module
APU
 
9.oo languages
9.oo languages9.oo languages
9.oo languages
APU
 
Design patterns structuralpatterns(theadapterpattern)
Design patterns structuralpatterns(theadapterpattern)Design patterns structuralpatterns(theadapterpattern)
Design patterns structuralpatterns(theadapterpattern)
APU
 

Mais de APU (10)

. 1. introduction to object orientation
. 1. introduction to object orientation. 1. introduction to object orientation
. 1. introduction to object orientation
 
. 01 introduction_to_module
. 01 introduction_to_module. 01 introduction_to_module
. 01 introduction_to_module
 
. 9. oo languages
. 9. oo languages. 9. oo languages
. 9. oo languages
 
. 8. design patterns
. 8. design patterns. 8. design patterns
. 8. design patterns
 
. 5. state diagrams
. 5. state diagrams. 5. state diagrams
. 5. state diagrams
 
. 4. class diagrams using uml
. 4. class diagrams using uml. 4. class diagrams using uml
. 4. class diagrams using uml
 
. 2. introduction to uml
. 2. introduction to uml. 2. introduction to uml
. 2. introduction to uml
 
. 01 introduction_to_module
. 01 introduction_to_module. 01 introduction_to_module
. 01 introduction_to_module
 
9.oo languages
9.oo languages9.oo languages
9.oo languages
 
Design patterns structuralpatterns(theadapterpattern)
Design patterns structuralpatterns(theadapterpattern)Design patterns structuralpatterns(theadapterpattern)
Design patterns structuralpatterns(theadapterpattern)
 

10 exceptionsin java

  • 1. Exceptions in Java OOSSE - Programming with Java 21 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 exceptions 21 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 • InputMismatchException 21 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: 3 21 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 occurs 21 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 terminate 21 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 error 21 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 exceptions 21 Dec 2012 OOSSE - Java Lecture 9 16

Notas do Editor

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