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

论坛 期权论坛 脚本     
匿名技术用户   2020-12-28 19:37   751   0
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

分享到 :
0 人收藏
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

积分:7942463
帖子:1588486
精华:0
期权论坛 期权论坛
发布
内容

下载期权论坛手机APP