The difference between throws and throws in java exception handling

Exception system:

I found that in a lot of interviews, I would ask about the handling of exceptions. Let’s talk briefly with you! !
Abnormal system
Exception handling:
As we all know, there are two ways to handle exceptions: throw and catch.
Use throws or throw to
capture. Try catch.
Let’s talk about the two ways that exceptions are thrown below:

throws syntax:
1 method signature/declaration, that is, after the parameter list, use throws to declare the exception class name to be thrown.
2 throws can be followed by multiple exception class names, separated by a comma,
3 once the program is thrown If an exception
occurs , at the place where the method throws, the subsequent code will no longer execute ps: The method statement throws an exception, and it does not necessarily throw an exception. It is just possible to throw an exception.

Example:

 /**
     * 异常处理方式一: 抛出异常
     */
    public static void m1() throws ParseException,ArithmeticException{
    
    
        // 编译期异常,抛出
        Date date  = new SimpleDateFormat("yyyy-MM-dd").parse("2021年01月04日");
        System.out.println(date );

        // 运行时异常,可以抛出,也可以不主动处理.
        // 如果不主动处理,那么虚拟机默认就是将异常抛出
        System.out.println(1/0 );
    }

Manually throw:

Throw syntax:
1. Where needed, directly use the throw keyword + exception object to throw an exception 2. Throw
followed by an exception object

Insert picture description here

Example: Manually throw an exception demonstration:
Summary:

1 throw is followed by the exception object, throws the exception class name
2 throw is followed by an object, throws is followed by multiple class names
3 throw is used inside the method, and throws is used in the method signature

Guess you like

Origin blog.csdn.net/CV_Ming/article/details/112602897
Recommended