• JAVA-try-catch-finally-自定义异常例子(适合初学者)


    package com.net.xinfang.reflect;
    
    import java.io.IOException;
    import java.util.Scanner;
    
    /***
     * 运行try块有异常抛出转到catch块,执行完catch后再执行finally块 
     * 运行try块没有异常抛出,也要执行finally块
     * @author xinfang
     *
     */
    public class MyException implements Runnable {
    	@Override
    	public void run() throws NullPointerException  {
    		@SuppressWarnings("resource")
    		Scanner input = new Scanner(System.in);
    		System.out.println("请输入被除数:");
    		try {
    			int num1 = input.nextInt();
    			System.out.println("请输入除数:");
    			int num2 = input.nextInt();
    			if(num1>6 || num2>6){
    				throw new deException("您输入的是"+num1+","+num2+"大于6不能进行计算");
    			}
    			System.out.println(String.format("%d / %d = %d", num1, num2, num1 / num2));
    		}catch (Exception e) {
    			System.err.println("出现错误:被除数和除数必须是整数," + "除数不能为零。");
    			System.out.println(e.getMessage());
    			// e.printStackTrace();
    		}
    		finally {
    			System.out.println("finally");
    		}
    	}
    
    	public static void main(String args[]) throws IOException {
    		try {
    			MyException me = new MyException();
    			new Thread(me).start();
    		} catch (Exception e) {
    			e.printStackTrace();
    			e.getMessage();
    		}
    		finally{
    			
    		}
    	}
    }
    /***
     * 自定义异常类
     * @author xinfang
     *
     */
    class deException extends Exception  
    {  
    	private String msg;
    	private static final long serialVersionUID = 1L;
    	public deException(String msg)  
        {  
            super(msg); 
            this.setMsg(msg);
        }
    	public String getMsg() {
    		return msg;
    	}
    	public void setMsg(String msg) {
    		this.msg = msg;
    	}  
    }  
    
    

  • 相关阅读:
    团队作业3--需求改进&系统设计
    需求分析&原型设计
    团队项目作业1-团队展示
    结对编程
    APP案例分析之华为浏览器
    四则运算生成器做法思路
    关于PHP使用GD库生成的验证码无法在别处显示
    第二次课程心得
    两个程序代码
    5.8下午
  • 原文地址:https://www.cnblogs.com/xinfang520/p/7684625.html
Copyright © 2020-2023  润新知