Home > Java > javaTutorial > body text

Comprehensive understanding of the exception handling mechanism in java

高洛峰
Release: 2017-01-05 14:55:24
Original
1227 people have browsed it

1. Summary of java exceptions:

Exceptions are abnormal operating conditions when the program is running.

1. Origin of exceptions:

Reflection on reality in the form of java classes Description of problems in things and sealed into objects

In fact, it is the object manifestation of java's description of abnormal situations

2. There are two ways to classify problems: one is serious The problem is a non-serious problem

For serious problems, java uses the Error class to describe it

For Error, generally no targeted code is written to handle it

For non-serious ones, java uses the Exception class to describe them.

Exceptions can be handled in a targeted way.

3. Common exceptions include: array subscript out-of-bounds exception, null pointer exception ……

4. Both Error and Exception have some common contents.

For example: messages about abnormal situations, causes, etc.

Throwable //Parent class (extracted from the same common features of the following two classes)

|--Error

|--Excption //Two subclasses (inside Many problems are defined (exceptions occur)) /*The parent class name is used as the suffix name of the subclass*/

Instance 1: Exception example

class Demo 
{
  public int div(int x,int y)
  {
    return x/y;
  }
}
 
 
class ExceptionDemo
{
  public static void main(String args[])
  {
    Demo d=new Demo();
    int x=d.div(4,0);  //0作为除数
    System.out.println("x="+x);
    System.out.println("over");
  }
}
Copy after login

Running result:

Exception in thread "main" java.lang.ArithmeticException: / by zero

at Demo.div(ExceptionDemo.java:5)

at ExceptionDemo.main(ExceptionDemo.java:15 )

It can be analyzed from the above results that exceptions occurred in lines 5 and 15. This is because of the division mechanism. The divisor cannot be 0. At this time, an exception is thrown during operation. .

Example 2: Exception occurredExample 2, memory overflow

class Demo
{
  public int div(int x,int y)
  {
    return x/y;
  }
}
 
 
class ExceptionDemo
{
  public static void main(String args[])
  {
    /*Demo d=new Demo();
    int x=d.div(4,0);
    System.out.println("x="+x);
    System.out.println("over");
    */
    byte[] arr=new byte[1024*1024*1000];
  }
}
Copy after login

Run result:

Exception in thread "main" java.lang.OutOfMemoryError: Java heap space
at ExceptionDemo.main(ExceptionDemo.java:19)

java.lang.OutOfMemoryError: Represents memory overflow exception

2. Exception handling:

For exception handling, java provides unique statements for processing

Format

try

{ 

 The code that needs to be detected;

}

catch

{

Code for handling exceptions; (handling method)

}

finally

{

Code that will definitely be executed; (processing method)

}

Example 1: Demonstrate try catch statement

class Demo
{
  public int div(int x,int y)
  {
    return x/y;
  }
}
 
 
class ExceptionDemo
{
  public static void main(String args[])
  {
    Demo d=new Demo();
    try
    {
      int x=d.div(4,0);
      System.out.println("x="+x);
    }
    catch(Exception e)
    {
      System.out.println("除数有误");
    }
     
    System.out.println("over");
     
    /*byte[] arr=new byte[1024*1024*1000];*/
  }
}
Copy after login

Running results:

Incorrect divisor

over

Result analysis: When the program is running, when the division statement: return x/y is executed, an abnormal object new is generated. AritchmeticException(), the try statement allows this object to be captured by the parameters of the catch statement

Exception e =new AritchmeticException();

After running the catch processing statement, the problem is processed and ends Statement, output over

Instance 2: Perform common method operations on the captured exception object (method of parent class Throwable)

String getMessage(); //Get exception information

toString() //Return exception name: exception information

printStackTrace() //Output exception name, exception information, exception location

class Demo
{
  public int div(int x,int y)
  {
    return x/y;
  }
}
 
 
class ExceptionDemo
{
  public static void main(String args[])
  {
    Demo d=new Demo();
    try
    {
      int x=d.div(4,0);
      System.out.println("x="+x);
    }
    catch(Exception e)
    {
      System.out.println("除数有误");
      //获得异常信息
      System.out.println(e.getMessage());
      //获得异常信息,异常名称
      System.out.println(e.toString());
      //输出异常名称,异常信息,异常出现的位置
      e.printStackTrace();         
    }
     
    System.out.println("over");
     
    /*byte[] arr=new byte[1024*1024*1000];*/
  }
}
Copy after login

Run result:

Incorrect divisor

/ by zero
java.lang.ArithmeticException: / by zero
java.lang.ArithmeticException: / by zero

at Demo. div(ExceptionDemo.java:5)

at ExceptionDemo.main(ExceptionDemo.java:17)

over

From the analysis of the running results, in fact The default exception handling mechanism of jvm is to call the printStackTrace method.

Example 3: Two ways to handle thrown exceptions

1. Throw it to the jvm virtual machine for processing

2. Handle the thrown exception yourself

class Demo
{
  public int div(int x,int y)throws Exception    /*有可能出现异常的地方抛出异常*/
  {
    return x/y;
  }
}
 
 
class ExceptionDemo
{
  public static void main(String args[])
  {
    Demo d=new Demo();  
    int x=d.div(4,0);
    System.out.println("x="+x);    
    System.out.println("over");    
  }
}
Copy after login

Run result:

ExceptionDemo.java:15: Error: Unreported exception error Exception; it must be caught or declared to
throw
int x=d.div (4,0);
^

1 error

Result analysis: This is because there is no handling of possible exceptions

Handling method 1: Keep throwing exceptions and let the jvm virtual machine handle it by itself

class Demo
{
  public int div(int x,int y)throws Exception    /*有可能出现异常的地方抛出异常*/
  {
    return x/y;
  }
}
 
 
class ExceptionDemo
{
  public static void main(String args[])   throws Exception  /*继续抛出异常,给虚拟机*/
  {
    Demo d=new Demo();  
    int x=d.div(4,0);
    System.out.println("x="+x);    
    System.out.println("over");    
  }
}
Copy after login

Processing method 2: Handle the exception by yourself

class Demo
{
  public int div(int x,int y)throws Exception    /*有可能出现异常的地方抛出异常*/
  {
    return x/y;
  }
}
 
 
class ExceptionDemo
{
  public static void main(String args[])   
  {
    Demo d=new Demo();
    try                   //自己处理异常
    {
      int x=d.div(4,0);
      System.out.println("x="+x);
    }
    catch(Exception e)
    {
      System.out.println("除数有误");
      //获得异常信息,异常名称
      System.out.println(e.toString());  
      System.out.println("over");  
    }
  }
}
Copy after login

Summary:

Declare the exception on the function. To improve security, let the callout handle the processing and not handle compilation failures.

Example 4: Handling multiple exceptions

1. When declaring an exception, it is recommended to declare a more specific exception, so that the processing can be more specific

2. Declare several Exceptions correspond to several catch blocks. Do not define redundant catch blocks.

If there is an inheritance relationship between exceptions in multiple catch blocks, the parent class exception catch block is placed below.

class Demo
{
  public int div(int x,int y)throws ArithmeticException,ArrayIndexOutOfBoundsException    
  {
    int arr[]=new int [x];
    System.out.println(arr[4]);
    return x/y;
  }
}
 
 
class ExceptionDemo
{
  public static void main(String args[])   
  {
    Demo d=new Demo();
    try                  
    {
      int x=d.div(4,0);
      System.out.println("x="+x);
    }
    catch(ArithmeticException e)          /*除法法则异常对象接收,第一个执行*/
    {
      System.out.println("除数有误");
      //获得异常信息,异常名称
      System.out.println(e.toString());  
      System.out.println("over");  
    }
    catch(ArrayIndexOutOfBoundsException e)    /*数据越界的对象接收,第二个执行*/
    {
      System.out.println("数组越界了");
      //输出异常信息
      System.out.println(e.toString());
    }
    catch(Exception e)               /*父类Exception接收,最后执行,建议不要写这个,让程序终止*/ /*用到了多态*/
    {
      System.out.println(e.toString());
    }
  }
}
Copy after login

Run result:

The array is out of bounds
java.lang.ArrayIndexOutOfBoundsException: 4

Suggestion:

Build in catch processing When doing this, the specific processing method must be defined in the catch

Do not simply define a sentence e.printStackTrace().

Do not simply write an output statement

Because the user sees If you don’t understand, it’s best to save it to a file and send it to our developers regularly for review.

Example 5: Custom exception

Have you noticed that the exceptions we are using are all encapsulated in java

But in actual development, our program The exception that appears in java may not be encapsulated.

At this time, you need to define it yourself

Based on the above code, I defined that the divisor cannot be a negative number. The code is as follows

class Demo
{
  public int div(int x,int y)throws FuShuException  /*抛出异常*/  
  {
    if(y<0)
    {
      throw new FuShuException("分母出现负数了------/bu FuShu",y);  /*自己手动抛出异常的对象*/
    }
    return x/y;
  }
}
class FuShuException extends Exception
{
  private int value;
  FuShuException(String m,int value)
  {
    super(m);                  /*给父类Exception的getMessage方法传递参数*/
    this.value=value;
  }  
  public int getValue()              /*自定义的方法,返回负数*/
  {
    return value;
  }
}
 
class ExceptionDemo
{
  public static void main(String args[])   
  {
    Demo d=new Demo();
    try                              
    {
      int x=d.div(4,-3);
      System.out.println("x="+x);
    }
    catch(FuShuException e)          /*捕获异常对象*/
    {
      System.out.println(e.getMessage()+e.getValue());
    }
    System.out.println("over");
  }
}
Copy after login

Run result:

The denominator is negative ------/bu FuShu-3
over

从上面的结果,可以看出

在本程序中,对于除数是-3,也视为是错误的是无法进行运算的。

那么就需要对这个问题进行自定义的描述。

当在函数内部出现了throw抛出异常对象,那么就必须要给对应的处理动作。

要么在内部try catch处理。

要么在函数上声明让调用者处理。

一般情况在,函数内出现异常,函数上需要声明。

发现打印的结果中只有异常的名称,却没有异常的信息。

因为自定义的异常并未定义信息。

如何定义异常信息呢?

因为父类中已经把异常信息的操作都完成了。
所以子类只要在构造时,将异常信息传递给父类通过super语句。
那么就可以直接通过getMessage方法获取自定义的异常信息。

自定义异常必须是自定义类继承Exception。

继承Exception原因:

异常体系有一个特点:因为异常类和异常对象都被抛出。

他们都具备可抛性。这个可抛性是Throwable这个体系中独有特点。

只有这个体系中的类和对象才可以被throws和throw操作。

throws和throw的区别

throws使用在函数上。

throw使用在函数内。

throws后面跟的异常类。可以跟多个。用逗号隔开。

throw后跟的是异常对象。

实例6:Exception中有一个特殊的子类异常RuntimeException 运行时异常

如果在函数内容抛出该异常,函数上可以不声明,编译一样通过。

如果函数上声明了该异常,调用者可以不进行处理,编译一样通过

之所以不用在函数声明,是因为不需要让调用者处理

当该异常发生,希望程序停止,因为在运行时,出现了无法运行的情况,希望程序停止后

程序员对该代码进行修改。

class Demo
{
  public int div(int x,int y)throws FuShuException   /*抛不抛结果都一样*/
  {
    if(y<0)
    {
      throw new FuShuException("分母出现负数了------/bu FuShu",y);  
    }
    return x/y;
  }
}
class FuShuException extends RuntimeException     /*继承RuntimeException*/
{
  FuShuException(String m,int value)
  {
    super(m);                  
     
  }  
}
 
class ExceptionDemo
{
  public static void main(String args[])   
  {
    Demo d=new Demo();
    int x=d.div(4,-3);              /*运行到这会出现异常,编译没有问题*/
    System.out.println("x="+x);
    System.out.println("over");
  }
}
Copy after login

运行结果:

Exception in thread "main" FuShuException: 分母出现负数了------/bu FuShu
at Demo.div(ExceptionDemo.java:7)
at ExceptionDemo.main(ExceptionDemo.java:26)

从上面的结果可以看出:

自定义异常时:如果该异常的发生,无法在继续进行运算,
就让自定义异常继承RuntimeException。

对于异常分两种:

1,编译时被检测的异常。

2,编译时不被检测的异常(运行时异常。RuntimeException以及其子类)

以上这篇全面理解java中的异常处理机制就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持PHP中文网。

更多全面理解java中的异常处理机制相关文章请关注PHP中文网!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template