</pre><pre name="code" class="java">class Test
{
//throws 在指定的方法中不处理异常,在调用此方法的地方处理
int div(int a ,int b) throws ZeroException, FushuException
{
if(b<0)
{
throw new FushuException("输入的除数"+b+"为负数,除数不能为负数");
}
if(b==0)
{
throw new ZeroException("输入的除数为0,除数不能为0!");
}
return a/b;
}
}
/*自定义异常 Start*/
class ZeroException extends Exception
{
public ZeroException (String msg)
{
super(msg); //调用Exception类中的构造方法,存入异常信息
}
}
class FushuException extends Exception
{
public FushuException(String msg )
{
super(msg);
}
}
/*自定义异常 End*/
public class TestException_2
{
public static void main(String[ ] args)
{
Test t=new Test( );
//捕获异常
try
{
t.div(6,-3);
}
catch(ZeroException x)
{
System.out.println(x.getMessage( ) );
x.printStackTrace( );
}
catch (FushuException e)
{
System.out.println(e.getMessage( ) );
e.printStackTrace( );
}
catch(Exception z)
{
System.out.println(z.getMessage( ) );
z.printStackTrace( );
}
}
}
/*
[小结]
自定义异常:
class 异常类名 extends Exception
{
public 异常类名(String msg)
{
super(msg);
}
}
2.标识出可能抛出的异常:
throws 异常类名1,异常类名2....等
3,捕获异常
getMessage( ) //输出异常信息
printStackTrace( ) //输出 异常名称 异常信息 异常出现的位置
*/