Java exception

1、 Abnormal?

Java. In Java System Lang. throwable class is the root class of the exception

[java.lang.throwable is the top-level class for all exceptions or errors, and can handle any exception]

* java.lang.Throwable
 * 		|-----java.lang.Error:一般不编写针对性的代码进行处理。
 * 		|-----java.lang.Exception:可以进行异常的处理
 * 			|------编译时异常(checked)
 * 					|-----IOException
 * 						|-----FileNotFoundException
 * 					|-----ClassNotFoundException
 * 			|------运行时异常(unchecked,RuntimeException)
 * 					|-----NullPointerException
 * 					|-----Arrayindexoutofboundsexception
 * 					|-----ClassCastException
 * 					|-----NumberFormatException
 * 					|-----InputMismatchException
 * 					|-----ArithmeticException

2、 Anomaly classification

Throwable is the top level class for all exceptions or errors and can handle any exception

Because the processing range is too large and the operation is inconvenient, Java provides two subclasses: exception and error

Exceptions are divided into: exception (treatable) and error (incurable)

1. Error:

It usually refers to the error in Java system, which has nothing to do with Java program Code cannot be used to maintain or modify errors

2. Exception:

It usually refers to errors in Java programs, which can be modified or maintained by code [usually value learning / research exception.]

Exception classification: [according to whether XX exception is checked at compile time]

Exception to be checked [non runtime exception]: refers to the exception to be checked when compiling a java file into a class file

No need to check exception [runtime exception]: refers to the exception that does not need to be checked when java files are compiled into class files

3. Which exceptions are exceptions to be checked and which exceptions are exceptions not to be checked?

Exception and its subclass [excluding runtimeException] belong to the required exception [non runtime exception]

RuntimeException and its subclasses belong to exceptions that do not need to be checked, that is, runtime exceptions

4. Common exceptions to be checked (compile time exceptions):

Syntax error, path error, etc

5. Common exceptions that do not need to be checked (runtime exceptions):

Array subscript out of bounds: Java Lang. ArrayIndexOutOfBoundsException, a java program attempts to access an element corresponding to a nonexistent index

Divisor 0: Java Lang. arithmeticexception: / by zero, in the computer, the divisor cannot be 0

Null pointer: Java Lang. NullPointerException: a java program attempts to access a property or method of an object that does not exist, so an error is reported

3、 Exception handling

Use try catch finally to handle compile time exceptions, so that the program will not report errors at compile time, but it may still report errors at run time

Because runtime exceptions are common in development, it is not usually try catch finally for runtime exceptions, but for compile time exceptions, we must consider exception handling

The throw method knowledge throws the exception to the caller of the method, and does not really handle the exception

1. The first kind: [actively deal with]

try{

存放可能发生异常的代码,try代码块将自动捕捉异常

}catch(异常类型  参数){

与发生的异常进行匹配,匹配上后将执行此处代码

}catch(异常类型  参数){

与发生的异常进行匹配,匹配上后将执行此处代码

}finally{

作为程序最后执行的代码,一定会执行,即使try和catch里面有return或异常

}

explain:

Principle:

Note: when there are multiple catch code blocks, put the exceptions with large processing range behind

When the exception object in the try matches a catch, it will enter the catch for exception processing. Once the processing is completed, it will exit the current try catch structure (when finally is not written) and continue to execute the subsequent code

Common processing methods:

They all print error messages in different ways

public void test1() {
		String str = "abc";
		try {
			int num = Integer.parseInt(str);
		}catch(Exception e) {
			// 1. System.out.println(e.getMessage());
            
			// 2. e.printStackTrace();
		}
	}

Shortcut operation

2. The second kind: [negative treatment]

格式: 

权限.... 方法名(参数类型 参数名,参数类型 参数名,...) throws 异常类型,...{

方法体

}

Principle:

One of the rules for method overrides:

The exception type thrown by the method overridden by the class is not greater than the exception type thrown by the method overridden by the parent class

import java.io.FileNotFoundException;
import java.io.IOException;

public class OverrideTest {
	
	public static void main(String[] args) {
		OverrideTest test = new Overridetest();
		test.display(new SubClass());
	}

	
	public void display(SuperClass s){
		try {
			s.method();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
}

class SuperClass{
	
	public void method() throws IOException{
		
	}	
}

class SubClass extends SuperClass{
	public void method()throws FileNotFoundException{
		
	}
}

3. How to choose whether to use try catch finally or throws in development?

4、 Throw exception manually

throw

public class StudentTest {
	
	public static void main(String[] args) {
		try {
			Student s = new Student();
			s.regist(-1001);
			System.out.println(s);
		} catch (Exception e) {
//			e.printStackTrace();
			System.out.println(e.getMessage());
		}
	}
	
}


class Student{
	
	private int id;
	
	public void regist(int id) throws Exception {
		if(id > 0){
			this.id = id;
		}else{
//			System.out.println("您输入的数据非法!");
			//手动抛出异常对象,运行时异常,可以不用try-catch
//			throw new RuntimeException("您输入的数据非法!");
            
            // 必须进行try-catch
			throw new Exception("您输入的数据非法!");
            
			//错误的
//			throw new String("不能输入负数");
		}
		
	}

	@Override
	public String toString() {
		return "Student [id=" + id + "]";
	}
	
	
}

5、 Custom exception

How to customize exception classes?

public class MyException extends Exception{
	
	static final long serialVersionUID = -7034897193246939L;
	
	public MyException(){
		
	}
	
	public MyException(String msg){
		super(msg);
	}
}

In this case, the self-defined exception class is used

package com.atguigu.java2;

public class StudentTest {
	
	public static void main(String[] args) {
		try {
			Student s = new Student();
			s.regist(-1001);
			System.out.println(s);
		} catch (Exception e) {
//			e.printStackTrace();
			System.out.println(e.getMessage());
		}
	}
	
}


class Student{
	
	private int id;
	
	public void regist(int id) throws Exception {
		if(id > 0){
			this.id = id;
		}else{
			throw new MyException("不能输入负数");
		}
	}

	@Override
	public String toString() {
		return "Student [id=" + id + "]";
	}
	
	
}

6、 Question

Enter a - use method a - create an exception - enter method B - call B

1. Please explain the difference between error and exception?

2. Please explain the exception handling process in Java

3. Please explain the difference between runtimeException and exception? Please list several common runtimeexceptions

7、 Summary

The difference between throw and throws: throw represents the process of throwing an object of an exception class and generating an exception object. The declaration is in the method body. Throws is a way of exception handling, which is declared at the declaration of the method.

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>