Common exceptions in Java

try-catch-finally

try{
    
    
//可能会抛出的异常
}catch{
    
    
//对异常进行处理
}finally{
    
    
//一定会执行的代码
}

Exception class
Error: system error, the program cannot handle
Exception: error during program operation, the program can handle

Error and Exception are both subclasses of Throwable. Throwable, error, and Exception are all stored in the java.lang package.

Common subclasses of Error: VirtualMachineError, AWTError, IOError
Common subclasses of VirtualMachineError: StackOverflowError, OutOfMemoryError, used to describe system problems such as memory overflow.
Common subclasses of Exception: IOException and RuntimeException
IOException is stored in the Java.io package, RuntimeException is stored in java.lang
Common subclasses of IOException: FileLockInterruptException, FileNotFoundException, FileException, these exceptions are handled when file transmission through IO stream The error that occurred.

Common subclasses of RuntimeException:

  • Mathematical operation exception: ArithmeticException
  • Class undefined exception: ClassNotFoundException
  • Parameter format error: illelArgumentException
  • Array index out of bounds: ArrayIndexOutOfBounds
  • Null pointer exception: NullPointException
  • Method is defined exception: NoSuchMethodError
  • The exception that occurs when other data types are converted to numeric types that do not match: NumberFormatException

Write your own logic and throw exceptions, which is more responsible than handing over to the virtual machine to handle it! Don't leave everything to others, so virtual opportunities are very tiring

public class Test{
    
    
	public static void main(String []args){
    
    
		int[] array = {
    
    1,2,3};
		test(array,2);
	}
	public static void test(int[]array,int index){
    
    
		if(index>=3||index<0){
    
    
		try{
    
    
		throw new Exception();
			}catch (Exception e){
    
    
		e.printStackTrace();
		}
		}else{
    
    
		System.out.println(array[index]);
		}
	}
}

Exception capture:
automatic capture, throw modification may throw exceptions, throws modification may throw exceptions

Custom exceptions: you can customize exceptions according to requirements

public class MyNumberException extends Exception{
    
    
	pubic MyNumberException (String error){
    
    
		super(error);
	}
}
public class Test{
    
    
public static void main(String []args){
    
    
}
public int add(Object object) throws MyNumberException {
    
    
	if(object instanceof Integer){
    
    
		int num =(int)object;
		return ++num;
	}else{
    
    
		String error = "Error";
		MyNumberException myError = new MyNumberException throw myError ;
	}
  }
}

Guess you like

Origin blog.csdn.net/A_Tu_daddy/article/details/112918395