Java learning (six): the exception mechanism

6.1 steering problem

  • Exception handling (Exception Handling) is a mechanism to solve this problem, better able to handle the situation the program may not run correctly.
    example

6.2 unusual concept

  • Abnormal means abnormal phenomenon occurring during program execution, such as user input errors, division by zero, the file to be processed does not exist, the array subscripts crossing the boundary.
  • In the Java exception handling mechanism, the introduction of many used to describe and handle exceptions class, called exception class . Exception class definition contains information such abnormality and method of abnormality processing.
  • The so-called exception handling , meaning the program can still finish in the correct implementation when problems arise.
  • Java is an object-oriented approach to handle exceptions . Process:
  1. Throws an exception : in the implementation of a method, if an exception occurs, this method generates an object representing the anomaly, stop the current execution path, and the exception object submitted to the JRE.
  2. Capture exception : the exception is obtained after JRE, find the appropriate code to handle the exception. JRE look at the call stack method, starting from the method generates an exception back until you find the appropriate exception handling code so far.

6.3 malfunction classification

  • Java abnormal classify different types of abnormalities are different Java classes, he said the root class for all exceptions java.lang.Throwable, Throwable has derived the following two subclasses: Error and Exception.
    classfication

6.3.1 Error

  • Error is an error in the program can not handle, indicate more serious problems running the application. Most errors unrelated to the operation and execution of code writers, and that the problem code is running JVM (Java Virtual Machine) appears. For example, Java virtual machine runtime error (Virtual MachineError), when the JVM is no longer required memory resources to continue operations, OutOfMemoryError will appear. When these exceptions occur, the Java Virtual Machine (JVM) will generally choose to terminate a thread .
  • JVM Error indicates that the system is already in a state of collapse unrecoverable. We do not ignore it.

6.3.2 Exception

  • Exception is an abnormal program itself can be processed, such as:
    null pointer exception (a NullPointerException)
    array subscript bounds exception (An ArrayIndexOutOfBoundsException)
    type conversion exception (a ClassCastException)
    arithmetic exception (an ArithmeticException) and the like.

    Exception class for all exception classes parent class , subclass corresponds to a wide variety of unusual events that may occur. Java exceptions usually can be divided into:

  1. RuntimeException runtime exception

  2. CheckedException checked exceptions

6.3.3 RuntimeException runtime exception

  • Derived RuntimeException exceptions , such as by 0 , array subscript bounds , null pointer , etc., which generates more frequent, troublesome process, if the impact statement or an explicit program will capture the readability and great operating efficiency. Thus automatically detected by the system and to their default exception handler (user does not have to handle them).
  • Such anomalies are usually caused by a programming error, so the preparation process is not required to use exception handling mechanism to deal with such exceptions, often need to increase the " logic processing to avoid these anomalies ."
  • ArithmeticException exception: trying to divide by zero
    example
  • A NullPointerException
    solution null pointer exception, typically increase non-empty Analyzing
    example
  • ClassCastException.
    example
  • ArrayIndexOutOfBoundsException Abnormal
    resolve array index out of bounds abnormal increase judgment on border
    example
  • A NumberFormatException
    digitally formatted abnormality resolved, the regular expression can be introduced is determined whether the digital
    example

6.3.4 CheckedException checked exceptions

  • All is not RuntimeException exceptions, collectively referred to as the Checked Exception , also known as " checked exceptions " such as IOException , SQLException , etc. as well as user Exception custom exception . Such an exception must be made at compile time, otherwise will not compile.

6.4 异常的处理方式之一:捕获异常

  • 捕获异常是通过3个关键词来实现的:try-catch-finally。用try来执行一段程序,如果出现异常,系统抛出一个异常,可以通过它的类型来捕捉(catch)并处理它,最后一步是通过finally语句为异常处理提供一个统一的出口,finally所指定的代码都要被执行(catch语句可有多条;finally语句最多只能有一条,根据自己的需要可有可无)
    note
  1. 即使 try 和 catch 块中存在 return 语句,finally 语句也会执行。是在执行完 finally 语句后再通过 return 退出。

  2. finally 语句块只有一种情况是不会执行的,那就是在执行 finally 之前遇到了 System.exit(0) 结束程序运行。
    example
    result

6.5 异常的处理方式之二:声明异常

  • 当CheckedException产生时,不一定立刻处理它,可以再把异常throws出去。
  • 在方法中使用try-catch-finally是由这个方法来处理异常。但是在一些情况下,当前方法并不需要处理发生的异常,而是向上传递给调用它的方法处理。
  • 如果一个方法中可能产生某种异常,但是并不能确定如何处理这种异常,则应根据异常规范在方法的首部声明该方法可能抛出的异常。
  • 如果一个方法抛出多个已检查异常,就必须在方法的首部列出所有的异常,之间以逗号隔开。
    example
    result

6.6 自定义异常

  1. 在程序中,可能会遇到JDK提供的任何标准异常类都无法充分描述清楚我们想要表达的问题,这种情况下可以创建自己的异常类,即自定义异常类。

  2. 自定义异常类只需从Exception类或者它的子类派生一个子类即可。

  3. 自定义异常类如果继承Exception类,则为受检查异常,必须对其进行处理;如果不想处理,可以让自定义异常类继承运行时异常RuntimeException类。

  4. 习惯上,自定义异常类应该包含2个构造器:一个是默认的构造器,另一个是带有详细信息的构造器。
    example

package io.github.amarisex;

public class TestMyException {
	public static void main(String[] args) {
		Person p = new Person();
		p.setAge(-1);
	}

}

class Person{
	private int age;

	public int getAge() {
		return age;
	}

	public void setAge(int age) {
		if(age<0) {
			throw new IllegalAgeException("negative age!");
		}
		this.age = age;
	}
	
}

class IllegalAgeException extends RuntimeException{
	public IllegalAgeException() {	
	}
	
	public IllegalAgeException(String msg) {	
		super(msg);
	}
	
}

result

  • 使用异常机制的建议
  1. To avoid the use of exception processing instead of the processing error , this will reduce the clarity of the program, and inefficient.

  2. Handling exceptions can not replace a simple test - using only exception mechanism in exceptional circumstances.

  3. Do not make exception handling small size - the entire task should be wrapped in a try block.

  4. Often abnormal in treatment of high

6.7 summary

  1. Error and Exception class inherits from Throwable

  2. Error class hierarchy describes internal errors and resource exhaustion system Java runtime error.

  3. Exception class is the parent class of all exception classes, subclasses correspond to the wide variety of unusual events that may occur.

  4. Common types of exceptions

    –ArithmeticException

    –NullPointerException

    –ClassCastException

    –ArrayIndexOutOfBoundsException

    –NumberFormatException

  5. Method override abnormal declared principles: a subclass declared abnormal range can not exceed the range of the parent class declaration

  6. Three ways to exception handling

    - catch exceptions: try-catch-finally

    - unusual statement: throws

  7. Custom exception class is derived from a subclass can only Exception class or its subclass.

Published 40 original articles · won praise 12 · views 5709

Guess you like

Origin blog.csdn.net/weixin_43488958/article/details/104529923