package com.imooc; //import java.util.Scanner; public class ThrowException { public static void main(String[] args) { ThrowException t1=new ThrowException(); try{ t1.test(); }catch (Exception e){ e.printStackTrace(); System.out.println(e.getMessage()); } } public void divide(int one,int two) throws Exception{ //Scanner input=new Scanner(System.in); //System.out.println("请输入第一个数字"); //int one=input.nextInt(); //System.out.println("请输入第二个数字"); //int two=input.nextInt(); if(two==0){ throw new Exception("两数相除,除数不为零"); }else{ System.out.println("两数相除的结果为:"+one/two); } } public void test() throws Exception{ ThrowException t2=new ThrowException(); t2.divide(5,0); } }
try必须要与代码块catch/finally一起使用,学会使用抛出异常的方法