第三个例子是自定义的啊,输出结果: Exception: "firstException()" method occurs an exception! book.exception.MyFirstException: "firstException()" method occurs an exception! at book.exception.TestMyException.firstException(TestMyException.java:10) at book.exception.TestMyException.main(TestMyException.java:19)
package book.exception;
/** *//**
* 自定义异常类
* 第一种定义方式,继承Exception类
* @author joe
*
*/public class MyFirstException extends Exception ...{
/** *//**
* 序列化ID
*/
private static final long serialVersionUID = 1L; public MyFirstException() ...{
super();
}
public MyFirstException(String msg) ...{
super(msg);
}
public MyFirstException(String msg, Throwable cause) ...{
super(msg, cause);
}
public MyFirstException(Throwable cause) ...{
super(cause);
}
/** *//**
* 自定义异常类
* 第二种定义方法,继承Throwable类
* @author joe
*
*/public class MySecondException extends Throwable ...{ /** *//**
*
*/
private static final long serialVersionUID = 1L; public MySecondException() ...{
super();
}
public MySecondException(String msg) ...{
super(msg);
}
public MySecondException(String msg, Throwable cause) ...{
super(msg, cause);
}
public MySecondException(Throwable cause) ...{
super(cause);
}
}
/** *//**
* 自定义异常类的使用
* @author joe
*
*/
public class TestMyException ...{ public static void firstException() throws MyFirstException ...{
throw new MyFirstException(""firstException()" method occurs an exception! ");
}
public static void secondException() throws MySecondException ...{
throw new MySecondException(""secondException()" method occurs an exception! ");
}
public static void main(String[] args) ...{
try...{
TestMyException.firstException();
TestMyException.secondException();
} catch(MyFirstException e1) ...{
System.out.println("Exception: " + e1.getMessage());
e1.printStackTrace();
} catch(MySecondException e2) ...{
System.out.println("Exception: " + e2.getMessage());
e2.printStackTrace();
}
}
}
Exception: "firstException()" method occurs an exception!
book.exception.MyFirstException: "firstException()" method occurs an exception!
at book.exception.TestMyException.firstException(TestMyException.java:10)
at book.exception.TestMyException.main(TestMyException.java:19)
public static void main(String[] args)
{
try
{ Excep excep1=new Excep();
excep1.division(3,0);
}
catch(Myexception e)
{
System.out.println(e);
}
}
}
class Excep
{
public double division(int a,int b)throws Myexception//throws ArithmeticException
{
throw new Myexception("除数为0");
}
}
class Myexception extends Exception
{
public Myexception(String msg)
{
super(msg);
}
}