Java Study Notes ---- exception
This is a picture stolen from other websites. There are two types of exceptions: Error: An Error Exception that cannot be handled by the Program: Exception: throws, if a car fails, the car cannot handle it by itself, so it can only be handed over to someone to handle throw in the function body. This is a custom exception class. You can output your own defined exceptions. Note: This throw also requires throws MyException. At first, I thought it was unnecessary. So the error code is:
Package com. ehealth. exc; import java. lang. exception; public class ExcTest {static int question (int x, int y) throws MyException {if (y <0) {throw new MyException ("the divisor cannot be a negative number ");} return x/y;} static int que (int x, int y) throws MyException {if (x <0) {throw new MyException ("the first digit cannot be less than 0");} return x + y;} public static void main (String [] args) {// TODO Auto-generated method stub int x = 3; int y =-1; int I =-1; Int j = 1; try {int a = que (I, j);} catch (MyException e1) {// TODO Auto-generated catch block System. out. println (e1.getMessage ();} try {int res = question (x, y);} catch (MyException e) {System. out. println (e. getMessage ();} catch (ArithmeticException e) {System. out. println (e. getMessage ();} catch (Exception e) {System. out. println ("Other exceptions occurred in the program! ") ;}} Class MyException extends Exception {String message; public MyException (String Err) {message = Err;} public String getMessage () {return message ;}}