Simple to use java exception thrown throws and throw the

premise:

When testing a program, if you need to define its own exception, rather than the current existing anomaly, this time you need to use throws and throw, try-catch just a simple catch exceptions of course.

code show as below:

package org.axc.com.Action;

import java.lang.Exception; 
public class TestException { 
    public static void count(int x) throws MyException{
        if(x>0) {
            throw new MyException("发生了自定义的异常");
        }
    }
    
    public static void main(String[] args) {
//      自己定义的异常如下
        try {
            count(3);
        } catch (MyException e) {
            e.printStackTrace();
        }
        
//      通过try-catch正常触发的异常
        try {
            int num=1/0;
        }catch(Exception e) {
            System.out.println(e);
        }
    }
} 

class MyException extends Exception { // 创建自定义异常类 
  public MyException(String ErrorMessagr) { // 父类方法 
      super(ErrorMessagr); 
  } 
}

In fact, the use of throw is simple
first you have to define an exception class, because you have to throw yourself a never seen before abnormal
Second, you write a constructor that you define this exception class (you can call the parent class), because to throw an exception information write our own
again need to write throws XXX after the desired method throws an exception, and write the information you want to throw an exception (throw new XXX ( "custom exception information")) in the method
Finally, try {} catch (XXX e) {} called on demand defined

Exception original code:

Links: https://blog.csdn.net/hackersuye/article/details/84193536
feeling to see the original code, there are some harvest.

Guess you like

Origin www.cnblogs.com/Anxc/p/11329978.html