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;
	}  
}  


原文地址:https://www.cnblogs.com/xinfang520/p/7684625.html