The twelfth day of JAVA learning - exception Throwable, try catch, throws, custom exception

abnormal

Throwable superclass for all exceptions

Error, serious problems do not handle
Exception, exception class, the program itself can handle

RuntimeException, run-time exception, not handled by the compiler, if there is a problem, come back and modify the code
Non-RuntimeException, compile-time exception, the compiler must handle it, otherwise the program cannot be compiled

JVM's exception default handling scheme

The name, reason, and location of the program exception will be output on the console

Two exception handling methods try catch, throws

1、try catch

Format

try { the code that may cause an exception} catch (the exception class object name) { handle the action code of the exception class; }



Processing method: When the program in try encounters an exception when it is running, and the exception class in catch is the same, the system handles it according to catch and can continue to execute;

2、throws

Format:

Exception location + throws exception class name;

Processing method: Compile-time exceptions can not be processed temporarily, and will be processed later when the function is used, and the execution cannot be skipped;

Throwable

member methods of throwable

Throwable is the superclass of all exceptions, and the member methods here can be used by all exception classes

Among them, the exception information output by the member method of printStackTrack() is the most complete, and this method is generally called directly;

custom exception

Create a class that inherits Exception, and you can create a custom exception class.
When a set exception occurs in the program, use throws+exception class name after the method body declaration, and throw the exception object in the method body; code The difference between throws and throw
example

public void checkScore(int score) throws ScoreException(){
    
    
        if(score<0 || score>100){
    
    
            throw new scoreException();
        }else
        {
    
    
            System.out.println("分数正常");
        }

    }

Guess you like

Origin blog.csdn.net/weixin_52723971/article/details/110531984