Exceptions in Java(异常)

Errors

  An Error is any unexpected result obtained from a program during execution.

  Unhandled errors may manifest themselves as incorrect results or behavior, or as abnormal program termination.

  Errors should be handled by the programmer, to prevent them from reaching the user.

Some common types of program fault

  Logic errors - the program does not match the specification (e.g. the requirements, or design)

  Divide by zero

  Exceeding array bounds

  Using an uninitialised variable/object

  …

Error Handling

  Traditional Error Handling

Return a special value,

  e.g., -1 or EoF

  Shortcoming:

  hard to distinguish different errors

  programmer must remember the meaning of different values

  Have a global error handling routine, and use some form of “jump” instruction to call this routine when an error occurs

  Shortcoming:

  “jump” instruction (GoTo) are considered “bad programming practice”

 

Exceptions in Java

 Exceptions:

  In Java, errors can be handled by exceptions

  Exceptions act similar to method return flags, but can provide more meaningful information

  Exceptions can be handled at local and/or global levels

  The classification of exceptions in Java

 Error:

  For internal errors and exhaustion situations in runtime

  We cannot do too much for these errors

 Exception:

   Runtime Exception:

    The program has some bugs, e.g., number/0

    Again, we cannot do too much…

  Checked Exception:

    produced by failed or interrupted

    I/O operations, e.g., cannot find a file

        

deal:

Throwing and catching

  An exception can be thrown, i.e., do not handle the error in this method, but throw it to where it is called

    public void aMethod() throws Exception{

    }

 Or

  can be catch, i.e., handle it here.

    try{

      …

     } catch(ExceptionType e){

    //statements that handle the

     //exception

     }

 

public class Exceptiondemo {

  public static void main(String[] args) {

    Exceptiondemo ex=new Exceptiondemo();

    ex.divide(1, 0);

    }

    public void divide(int x, int y) throws ArithmeticException {

    int result= x/y;

    }

  }

 

public void divide(int x, int y) throws ArithmeticException {

  try{

    int result= x/y;

  }catch (ArithmeticException e){

    System.out.println("Cannot divided by 0!!");

     }

   }

 

The finally block

  The finally block always executes when the try block exits.

  This ensures that the finally block is executed even if an unexpected exception occurs.

  try {

     } catch (ExceptionType1> e) {

      // statements that handle the exception

    } catch (<ExceptionType2 e) {

      // statements that handle the exception

    } finally {

      // release resources

    }

posted @ 2017-12-18 12:29  CaiCongyu  阅读(228)  评论(0编辑  收藏  举报