Java的自定义异常

版权声明:本网站发表的文章,版权归原作者所有;不得转载。 https://blog.csdn.net/qq_41709494/article/details/88622514

根据上一篇的的调整:https://blog.csdn.net/qq_41709494/article/details/88602741

1.语法错误   (不能处理此类异常)
2.运行时异常
3.系统异常(Error ApplicationException)  (不能处理此类异常)
4.逻辑错误  (可以用自定义异常处理)

1.throws用于抛出方法层次的异常,
直接由些方法调用异常处理类来处理该异常,
所以它常用在方法的后面。

2.throw用于方法里面的代码,比throws的层次要低,比如try...catch...语句块,表示它抛出异常,
但它不会处理它,
而是由方法块的throws Exception来调用异常处理类来处理。

package cn.zzx.error;

/**
 * 
 * 自定义异常:
 * 构造方法,并且重载
 *
 */

public class TypeException extends Exception{
	public  TypeException(){
		super("请输入1-3之间的整数:");
	}
	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.喜欢\t2.一般\t3.不喜欢");
		System.out.println("******************");
		boolean error = false;   //开关按钮
		int input = 0;          //初始值input
		do{                      //直到型循环do怎样都执行一次
/**
 * 捕获异常执行的代码			
 */
		   try{  				
		Scanner scan = new Scanner(System.in);
		 input  = scan.nextInt();
		 if(input<1 ||input>3){       //判断小于1的数值与大于3的数值
				throw new TypeException();  //自定义异常的调用
				
			}
		 error = true ;          //迭代器
		
		
		   }     //执行do循环一次完成
/**
 * 捕获异常输出
 */
		catch(Exception e){
//			e.printStackTrace();
			System.out.println(e.getMessage());    //打印异常信息
			
//			System.out.println("出错了,请输入1-3之间的整数:");
//			throw new TypeException();
		
			
		  }
			
		}while(!error);	  //判断是否循环
		
			
		
		switch(input){
		   case 1:
			   System.out.println("喜欢");
			   break;
		   case 2:
			   System.out.println("一般");
			   break;
		   case 3:
			   System.out.println("不喜欢");
			   
			
			 }
		}

}

猜你喜欢

转载自blog.csdn.net/qq_41709494/article/details/88622514