Java custom exception

Posted by jboku on Wed, 04 Dec 2019 22:11:23 +0100

According to the adjustment of the previous article: https://blog.csdn.net/qq_41709494/article/details/88602741

1. Syntax error (such exception cannot be handled)
2. Abnormal operation
3. System exception (such exception cannot be handled)
4. Logical error (can be handled with custom exception)

1.throws is used to throw exceptions at the method level,
The exception handling classes are directly called by some methods to handle the exception,
So it's often used after methods.

2.throw is used for the code in the method, which is lower than the level of throws. For example, try...catch... Statement block means that it throws an exception,
But it doesn't deal with it,
Instead, the throws Exception of the method block calls the exception handler class to handle it.

package cn.zzx.error;

/**
 * 
 * Custom exception:
 * Construct method and overload
 *
 */

public class TypeException extends Exception{
	public  TypeException(){
		super("Please input 1-3 Integer between:");
	}
	public TypeException(String message){
		super(message);
	}

}
package cn.zzx.error;

import java.util.Scanner;

public class Anomaly {
	public static void main(String[] args){
		System.out.println("******************");
		System.out.println("1.like\t2.commonly\t3.Dislike");
		System.out.println("******************");
		boolean error = false;   //Switch button
		int input = 0;          //Initial value input
		do{                      //do is executed once, until
/**
 * Capture code executed abnormally			
 */
		   try{  				
		Scanner scan = new Scanner(System.in);
		 input  = scan.nextInt();
		 if(input<1 ||input>3){       //Judge values less than 1 and greater than 3
				throw new TypeException();  //Call of custom exception
				
			}
		 error = true ;          //iterator
		
		
		   }     //Execute do loop once to complete
/**
 * Capture exception output
 */
		catch(Exception e){
//			e.printStackTrace();
			System.out.println(e.getMessage());    //Print exception information
			
//			System.out.println("error, please enter an integer between 1-3:");
//			throw new TypeException();
		
			
		  }
			
		}while(!error);	  //Judge whether it is circular
		
			
		
		switch(input){
		   case 1:
			   System.out.println("like");
			   break;
		   case 2:
			   System.out.println("commonly");
			   break;
		   case 3:
			   System.out.println("Dislike");
			   
			
			 }
		}

}

Topics: Java less