. Java Exception Handling

Source: Internet
Author: User
Tags getmessage throwable

1. Java Exception Handling

Exceptions are errors in the program, but not all errors are exceptions, and errors can sometimes be avoided.

比如说,你的代码少了一个分号,那么运行出来结果是提示是错误 java.lang.Error;如果你用System.out.println(11/0),那么你是因为你用0做了除数,会抛出 java.lang.ArithmeticException 的异常。

Exceptions occur for a number of reasons, usually including the following categories:

用户输入了非法数据。要打开的文件不存在。网络通信时连接中断,或者JVM内存溢出

Some of these exceptions are caused by user errors, due to program errors, and others due to physical errors. -

To understand how Java exception handling works, you need to master the following three types of exceptions:

检查性异常:最具代表的检查性异常是用户错误或问题引起的异常,这是程序员无法预见的。例如要打开一个不存在文件时,一个异常就发生了,这些异常在编译时不能被简单地忽略。运行时异常: 运行时异常是可能被程序员避免的异常。与检查性异常相反,运行时异常可以在编译时被忽略。错误: 错误不是异常,而是脱离程序员控制的问题。错误在代码中通常被忽略。例如,当栈溢出时,一个错误就发生了,它们在编译也检查不到的。

Noun Explanation:

1.检查性异常: 不处理编译不能通过2.非检查性异常:不处理编译可以通过,如果有抛出直接抛到控制台3.运行时异常: 就是非检查性异常4.非运行时异常: 就是检查性异常

Question: What anomalies have we encountered?

2. Hierarchy of Exception classes

All exception classes are subclasses that inherit from the Java.lang.Exception class.

The Exception class is a subclass of the Throwable class. In addition to the exception class, Throwable also has a subclass error.

Java programs typically do not catch errors. Errors generally occur in the event of a serious failure, which is outside the scope of the Java program processing.

The error is used to indicate that a run-time environment has occurred.

For example, JVM memory overflows. In general, the program does not recover from the error.

The exception class has two primary subclasses: the IOException class and the RuntimeException class.

Java built-in exception class:

Non-inspection Exceptions:

ArithmeticException 当出现异常的运算条件时,抛出此异常。例如,一个整数"除以零"时,抛出此类的一个实例。ArrayIndexOutOfBoundsException  用非法索引访问数组时抛出的异常。如果索引为负或大于等于数组大小,则该索引为非法索引。ArrayStoreException 试图将错误类型的对象存储到一个对象数组时抛出的异常。ClassCastException  当试图将对象强制转换为不是实例的子类时,抛出该异常。IllegalArgumentException    抛出的异常表明向方法传递了一个不合法或不正确的参数。IllegalMonitorStateException    抛出的异常表明某一线程已经试图等待对象的监视器,或者试图通知其他正在等待对象的监视器而本身没有指定监视器的线程。IllegalStateException   在非法或不适当的时间调用方法时产生的信号。换句话说,即 Java 环境或 Java 应用程序没有处于请求操作所要求的适当状态下。IllegalThreadStateException 线程没有处于请求操作所要求的适当状态时抛出的异常。IndexOutOfBoundsException   指示某排序索引(例如对数组、字符串或向量的排序)超出范围时抛出。NegativeArraySizeException  如果应用程序试图创建大小为负的数组,则抛出该异常。NullPointerException    当应用程序试图在需要对象的地方使用 null 时,抛出该异常NumberFormatException   当应用程序试图将字符串转换成一种数值类型,但该字符串不能转换为适当格式时,抛出该异常。SecurityException   由安全管理器抛出的异常,指示存在安全侵犯。StringIndexOutOfBoundsException 此异常由 String 方法抛出,指示索引或者为负,或者超出字符串的大小。UnsupportedOperationException   当不支持请求的操作时,抛出该异常。

Check Exception class:

ClassNotFoundException  应用程序试图加载类时,找不到相应的类,抛出该异常。CloneNotSupportedException  当调用 Object 类中的 clone 方法克隆对象,但该对象的类无法实现 Cloneable 接口时,抛出该异常。IllegalAccessException  拒绝访问一个类的时候,抛出该异常。InstantiationException  当试图使用 Class 类中的 newInstance 方法创建一个类的实例,而指定的类对象因为是一个接口或是一个抽象类而无法实例化时,抛出该异常。InterruptedException    一个线程被另一个线程中断,抛出该异常。NoSuchFieldException    请求的变量不存在NoSuchMethodException   请求的方法不存在

Method of Exception:

The main methods of the Throwable class are:

1   public String getMessage()返回关于发生的异常的详细信息。这个消息在Throwable 类的构造函数中初始化了。2   public Throwable getCause()返回一个Throwable 对象代表异常原因。3   public String toString()使用getMessage()的结果返回类的串级名字。4   public void printStackTrace()打印toString()结果和栈层次到System.err,即错误输出流。5   public StackTraceElement [] getStackTrace()返回一个包含堆栈层次的数组。下标为0的元素代表栈顶,最后一个元素代表方法调用堆栈的栈底。6   public Throwable fillInStackTrace()用当前的调用栈层次填充Throwable 对象栈层次,添加到栈层次任何先前信息中。
3. Abnormal capture 3.1 try-catch capture 3.1.1 Try-catch single recapture

Use the try and catch keywords to catch exceptions. The Try/catch code block is placed where the exception can occur.

The code in the Try/catch code block is called the Protection Code, and the syntax for using Try/catch is as follows:

try{   // 程序代码}catch(ExceptionName e1){   //Catch 块}

The Catch statement contains the declaration to catch the exception type. When an exception occurs in the protection code block, the catch block after the try is checked.

If the exception that occurs is contained in a catch block, the exception is passed to the catch block, which is the same as passing a parameter to the method.

Instance:

In the following example, an array of two elements is declared, and an exception is thrown when the code attempts to access the third element of the array.

// 文件名 : ExcepTest.javaimport java.io.*;public class ExcepTest{   public static void main(String args[]){      try{         int a[] = new int[2];         System.out.println("Access element three :" + a[3]);      }catch(ArrayIndexOutOfBoundsException e){         System.out.println("Exception thrown  :" + e);      }      System.out.println("Out of the block");   }}

Operation Result:

Exception thrown  :java.lang.ArrayIndexOutOfBoundsException: 3Out of the block
3.1.2 Try-catch Multiple Capture

A try code block that follows multiple catch code blocks is called a multiple capture.

The syntax for the multiple capture block is as follows:

try{   // 程序代码}catch(异常类型1 异常的变量名1){  // 程序代码}catch(异常类型2 异常的变量名2){  // 程序代码}catch(异常类型2 异常的变量名2){  // 程序代码}

The preceding code snippet contains 3 catch blocks.

You can add any number of catch blocks after the try statement.

If there is an exception in the protection code, the exception is thrown to the first catch block.

If the data type that throws the exception matches the ExceptionType1, it is captured here.

If it does not match, it is passed to the second catch block.

So, until the exception is caught or through all the catch blocks.

try{  file = new FileInputStream(fileName);  x = (byte) file.read();}catch(IOException i){  i.printStackTrace();  return -1;}catch(FileNotFoundException f) //Not valid!{  f.printStackTrace();  return -1;}

We usually do the following in the catch statement:

   try{      可能出现异常的代码   }catch(异常类型 e){      处理异常:       1 打印到控制台       2 保存到文件       3 还可能向外抛出新的异常   }finally{      }
3.2 Throws/throw throws an exception

If a method does not capture an inspection exception, the method must be declared using the throws keyword. The throws keyword is placed at the tail end of the method signature.

You can also throw an exception with the Throw keyword, whether it's newly instantiated or just captured.

The declaration of the following method throws a RemoteException exception:

import java.io.*;public class className{  public void deposit(double amount) throws RemoteException  {    // Method implementation    throw new RemoteException();  }  //Remainder of class definition}

A method can declare that multiple exceptions are thrown, and multiple exceptions are separated by commas.

For example, the following method declarations throw remoteexception and insufficientfundsexception:

import java.io.*;public class className{   public void withdraw(double amount) throws RemoteException,                              InsufficientFundsException   {       // Method implementation   }   //Remainder of class definition}

The difference between throw and throws:

throws使用在函数上throw使用在函数内throws后面跟的是异常类,可以跟多个,逗号隔开throw后面跟的是异常对象
Handling of 3.3 finally exception

The finally keyword is used to create a block of code that executes after a try code block.

The code in the finally code block is always executed, regardless of whether an exception occurs.

In the finally code block, you can run an end-of-nature statement such as cleanup type.

The finally code block appears at the end of the catch code block, with the following syntax:

try{  // 程序代码}catch(异常类型1 异常的变量名1){  // 程序代码}catch(异常类型2 异常的变量名2){  // 程序代码}finally{  // 程序代码}

Instance:

public static void copy(File src,File des) {    BufferedReader br = null;    BufferedWriter bw = null;    try {        br = new BufferedReader(new FileReader(src));        bw = new BufferedWriter(new FileWriter(des));        char[] data = new char[4096];        int ch = 0;        while ((ch = br.read(data)) != -1) {            bw.write(data, 0, ch);        }    } catch (IOException e) {        e.printStackTrace();    }finally {        try {            if (br != null) {                br.close();            }            if (bw != null) {                bw.close();            }        } catch (IOException e) {            e.printStackTrace();        }    }}

This way, regardless of whether FileReader and FileWriter are instantiated successfully, the file exists, and finally we can close the two streams

We usually do the following in the finally code block:

1.关闭流资源(IO流部分讲解)或者 释放锁--线程(以后课程学习)    简单说明一下: 这里的流,类似于水流的意思,比如一个水龙头打开,流出水,突然发生地震了(产生异常),没有关闭水龙头,那水就一直流着,然后可能导致短路,电路中断,然后就可能引起火灾;所以希望中途不管发生什么异常情况,最终都应该关闭水龙头。这样就可以把关闭的代码写在finally里面;2.释放锁 比如上厕所需要上锁,然后完事了之后,最后在开锁出来。    特点:如果在finally前面没有执行系统退出(system.exit(0))的语句,此处的代码始终都会执行。3.不建议此处放return语句来返回一个数据(让程序难以理解,并且这里也不应该放return)对于上面的结构,也有变种,比如:try{}finally{}只有try-finally,没有catch,这种结构在讲线程,释放锁学习

Note the following items:

catch 不能独立于 try 存在。在 try/catch 后面添加 finally 块并非强制性要求的。try 代码后不能既没 catch 块也没 finally 块。try, catch, finally 块之间不能添加任何代码。
4. Declaring custom exceptions

The Java exception system already contains a lot of exception classes, but still can not meet the development of the daily situation that should do?

Scene:

   1。假设用户注册过程中,发现用户名重复了,把这种情况定义为异常类型;   2。设计一个用户注册的方法,方法里面判断用户注册的用户名是否重复,如果重复,就产生一个异常对象;   3。调用注册方法来注册一个账号,就会产生一个异常。产生异常之后,就选择是抛出还是处理.

Rules for custom Exceptions:

所有异常都必须是 Throwable 的子类。如果希望写一个检查性异常类,则需要继承 Exception 类。如果你想写一个运行时异常类,那么需要继承 RuntimeException 类。

1. Define an exception class (user name repeat exception)

package com.rimi.exception;public class NameRepeatException extends Exception {    public NameRepeatException(){        super();    }    public NameRepeatException(String msg){        super(msg);    }}

2. Write a test class

package com.rimi.lesson20;public class Test {    public static void main(String[] args) {        String[] names = { "张三", "李四", "王二", "麻子", };        try {            login("张三", names);        } catch (Exception e) {            // TODO: handle exception            System.out.println("异常抛出:" + e.getMessage());        }    }    public static void login(String name, String[] names) throws NameRepeatException {        for (String string : names) {            if (string.equals(name)) {                throw new NameRepeatException("名字重复了");            }        }    }}

Exception usage can follow the following guidelines:

1:在当前方法被覆盖时,覆盖他的方法必须抛出相同的异常或异常的子类;2: 在当前方法声明中使用try-catch语句捕获异常;3:如果父类抛出多个异常,则覆盖方法必须抛出那些异常的一个子集,不能抛出新异常。

. Java Exception Handling

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.