Exception handling (Exception Handling)

java, exception handling (Exception)
Exception is something undesirable occurring during program execution, these things if not properly treated, can lead to strange results or program termination. Exception Handler those dealing with the abnormality when an abnormality occurs in the code. So you talk about three thing here:

1. What is an exception (Exception)
1.1 Exceptions and in the Java
1.2 the checked and unchecked exceptions
1.3 error and unchecked exception different
2. How to handle exceptions (How to handle Exception)
2.1 the try-catch- a finally
2. 2. throws exception
3. how to create a custom exception class of
3.1 how to create a custom exception class of
how to throw a custom 3.2 throw the exception
1. What is an exception (Exception)
Exception occurred during program execution in a number of do not want to happen, these things if not properly treated, can lead to strange results or program termination. Exception Hander those dealing with the abnormality when an abnormality occurs in the code. java and javascript are treating exceptions try / catch.

Exceptions and in java 1.1
Exception in java, is also object.
To a first map


Source: http://voyager.deanza.edu/~hso/cis35a/lecture/java13/intro/hier.html
its father is Throwable (interview examination, knock on the blackboard). It also has a brother called Error.

Different error and exception of:
An Error IS A subclass of Throwable that indicates Serious Problems that A Reasonable the Application Should not the try to the catch.

at The class Exception and the ITS subclasses are A form of Throwable that indicates Conditions that A Reasonable the Application Might want to the catch.

the abnormal 1.2 checked and unchecked
Checked exception is when the compiler is required to be handle. Compile time will detect Checked exception if there is not handler (plus there is no handler) is also known as compile-time exception occurs. If a class is Exception but not RuntimeException children's children, then it is checked, when they were required to write code plus handler. If IDE, will be asked to handle such exceptions when writing code.
For example: CloneNotSupportedException, IOException, SQLException,
InterruptedException, FileNotFoundException
Unchecked Exception is also known as runtime exception because it occurs during program execution. We can add a handler to deal with such exceptions may not add handler does not handle such exceptions. If a class is a descendant of RuntimeException, that it is an unchecked exception.
For example: IllegalMonitorStateException,
a ConcurrentModificationException, NullPointerException,
IndexOutOfBoundException, NumberFormatException
different 1.3 error and the unchecked exception
, although have occurred in the runtime, but the error is not recommended to handle. In most cases even increase the catch can not be repaired. The RuntimeException can go handle.

2. How to handle exceptions (how to handle exception)
there are ways to declare when it was declared a throw exception. If the exception is a checked exception, this method is called when you have to handle it.
checked exception is like a bomb, if somewhere throw a bomb Method A, or elsewhere received a bomb (another method called the thrown exception), there are two solutions:

own break it ( try-catch-finally). In this case call the method A method do not worry about the bomb (abnormal) a
Continue to throw out, who calls the method A Who processing (at the time of the declaration of method A plus throws.)
If the first option, when calling Method A Method B, Method A bomb has torn down, Method B do not worry about anything.
If the second method, Method B Method A call when you want to know at the same time received a bomb, so it has two solutions, torn down, or continue throws.

2.1 How to dismantle a bomb with the catch-a finally-the try
the try-the catch:
a common array bounds exception. It is unchecked the exception, because the handle does not require compile-time, so is a common novice runtime exception. (Not required to be handle, but if you want to handle are also possible.)

Import the java.io. *;
public class ExceptionTest1 {
   public static void main (String args []) {
      the try {
         int A [] = new new int [2];
         System.out.println (a [3]); // array of cross-border access to
      } the catch (ArrayIndexOutOfBoundsException E) {
         System.out.println (E); // Although there is no meaningful things to do, but prevents the program died in half .
      }
      System.out.println ( "RUN successfully");
   }
}

A try may be followed by several catch, in order to separate the different error handling:

try {
   // doing something
} the catch (Exception1 E) {
    // The handle type Exception First
    System.out.println ( "Exception1 Happened")
} the catch ( F Exception2) {
    // the first type handle exception
    System.out.println ( "Exception2 happened")
}

after the occurrence of an exception, if Exception1 type, will be a first handle, if not then it will Exception1 type looking down catch, if Exception2 type, will be the second catch block handle.
If Exception1 and Exception2 are parent-child relationship, the son must first be detected, because if my father was first detected, you never get to that son of a catch block.

block a finally:
a finally block is a block in any case will occur. catch in the code will not be executed if the exception does not occur, but finally execute the code inside anyway. (Except in the inside try or catch with System.exit (1) End JVM.) Is typically used to close the file.

      {the try
         // doing something
      The catch} (Exception E) {
          // The handle Exception
      } the finally {
         // code that will be executed.
      }
   }
}

In addition, try-finally is legal.

2.2 How to continue thrown pot throws exception
with throws keyword

// m1 throws an exception
void M1 throws FileNotFoundException () {
    // probably want to read some files, do not want to consider if the file is not found Zezheng. (Thrown pot)
}
// M2 called m1, the equivalent received from the hands of the exception m1, we do not deal with, continue thrown out.
M2 throws FileNotFoundException void () {
    m1 (); // want to use the method m1, m1 case statement I'm going to consider if you want to use the file can not be found.
    // m2 but still do not want to consider the file not found Zezheng.
}

View comprehensive examples:
The following exception code is not properly received due to the handle and a compiler error:

Import java.io.File;
Import java.io.FileReader;
// will compile error
public class ReadFileTest {
   static void main public (String args []) {
      the getFile ();
   }
   public static void the getFile () {
          File File = new new File ( "file.txt");
       the FileReader fr = new new the FileReader (File); // error: unreported FileNotFoundException Exception; the mUST bE Caught or declared to bE thrown
   }
}

because the FileReader constructor throws an exception

public FileReader (String fileName) throws FileNotFoundException
1
so when getFile FileReader method calls must handle the exception.

The following is an example of processing by the above two methods exception:

Import java.io.File;
Import java.io.FileReader;
Import java.io.FileNotFoundException;
public class ReadFileTest {
   public static void main (String args []) {
           getFile1 ( );
           System.out.println ( "=============");
        the try {
           // because getFile2 exception thrown out again, so that the main method of treatment available.
           getFile2 ();
        } the catch (a FileNotFoundException E) {
           System.out.println ( "Exception in the Handled main");
        }
      
   }
   // getFile1 choose their processing, no trouble call its methods
   public static void getFile1 () {
        the try {
                  File File = new new File ( "file.txt");
               the FileReader fr = new new the FileReader (File);
           } the catch (a FileNotFoundException E) {
               System.out.println ( "Exception getfile1 in the Handled");
       }
   }
   // selected getFile2 no treatment, continue throws
   static void getFile2 public () throws a FileNotFoundException {
          File File = new new File ( "file.txt");
       the FileReader fr = new new the FileReader (File);
   }
}

Run Results:

Exception in the Handled getfile1
========== ===
Exception in main the Handled

in general, all of the exception to the main method here should have been resolved. If, main method is also irresponsible to throw out. . .

java.io.File Import;
Import java.io.FileReader;
Import java.io.FileNotFoundException;
public class ReadFileTest {
   public static void main (String args []) {throws a FileNotFoundException
           getFile1 ();
           System.out.println ( "= ============ ");
        getFile2 ();
      
   }
   public static void getFile1 () {
        try{
                  File file = new File("file.txt");
               FileReader fr = new FileReader(file);
           }catch(FileNotFoundException e){
               System.out.println("Exception handled in getfile1");
       }
   }
   public static void getFile2() throws FileNotFoundException{
          File file = new File("file.txt");
       FileReader fr = new FileReader(file);
   }
}

这样做是可以的。。。在没有文件的情况下(触发exception)运行结果:

Exception handled in getfile1
=============
Exception in thread "main" java.io.FileNotFoundException: file.txt (No such file or directory)
    at java.io.FileInputStream.open0(Native Method)
    java.io.FileInputStream.open AT (FileInputStream.java:195)
    AT a java.io.FileInputStream. <the init> (FileInputStream.java:138)
    AT java.io.FileReader. <the init> (FileReader.java:72)
    AT ReadFileTest.getFile2 (ReadFileTest.java:21)
    AT ReadFileTest.main (ReadFileTest.java:8)

3. how to apply custom of exception
3.1 how to create a custom category of exception
extends exception and its children die

1. class New1Exception extends Exception {} // create an Exception the checked
2. class NewException the extends IOExcpetion {} // create a associated with the IO Exception
3. class NewException the extends RuntimeException {} // create a UnChecked exception

to example (is so simple):

Import the Java * .io;.
class MyException the extends Exception
{
    MyException public (String S)
    {
        Super ( "A MyException the happens:" + S);
        // can do something else
    }
}

3.2 how to throw (the throw) in a custom Exception
the throw and throws
the throw is a method or the code inside the block, an exception is thrown for bombs.
throws when the method is declared, indicating that this method throws an exception.

Write example with just MyException:

Import the java.io. *;
public class the Main
{
    public static void main (String args [])
    {
        the try {
            throwTest ();
        } the catch (MyException E) {
            System.out.println ( " something Caught ");
            System.out.println (e.getMessage ());
        }
        // throwTest2 is a normal method, throwing the handle by their own exception.
        throwTest2 ();
        // another block with a test Test3,
        // if written in the same block, throwTest () throws an exception, throwTest3 () is not executed,
        the try {
            throwTest3 ();
        } the catch (MyException E) {
            System.out.println ( "Caught something");
            System.out.println (e.getMessage ());
        }
    }
    // they do not handle, then throw them out in the method declaration goes on to tell the calling of their method requires handle
    public static throwTest void () {MyException throws
        the throw new new MyException ( "something");
    }
    // own handle, into a normal method
    public static void throwTest2 () {
        the try {
            the throw new new MyException ( "somethingElse");
        } the catch ( MyException e) {
            System.out.println ( "Caught somethingElse");
            System.out.println (e.getMessage ());
        }
    }
    // handle themselves, and continue to throw out the catch in.
    static void throwTest3 public () {MyException throws
        the try {
            the throw new new MyException ( "somethingElse2");
        } the catch (MyException E) {
           // an irresponsible catch, but is legal.
           E the throw;
        }
    }
}  

Output:

Caught something
A MyException the happens: something
Caught somethingElse
A MyException the happens: somethingElse
Caught something
A MyException the happens: somethingElse2

Guess you like

Origin www.cnblogs.com/zhuyeshen/p/10968244.html