自定义Exception

DaoException,ServiceException都是自定义异常类,
DaoException继承自ServiceException,ServiceException继承自Exception类。

显示代码:
 1 package com.wei.exception;
2
3 public class DaoException extends ServiceException{
4
5 public DaoException(){
6 super("dao层异常");
7 }
8
9 public DaoException(String msg){
10 super(msg);
11 }
12
13 public DaoException(Exception e){
14 super("dao层异常",e);
15 }
16
17 public DaoException(String msg , Exception e){
18 super(msg,e);
19 }
20 }
 1 package com.wei.dao.impl;
2
3 // class created by wwei 2011-12-11 下午01:32:45
4
5 public class DaoImpl {
6 public void testDaoExce() throws DaoException{
7 try {
8 User user = null;
9 user.printUser(); //空值调用方法,必报异常java.lang.NullPointerException
10 } catch (Exception e) {
11 throw new DaoException("dao层testDaoExce方法异常",e);
12 }
13 }
14 }
显示代码:
 1 package com.wei.exception;
2
3 // class created by wwei 2011-12-11 下午02:15:47
4
5 public class ServiceException extends Exception{
6 public ServiceException(){
7 super("service层异常");
8 }
9
10 public ServiceException(String msg){
11 super(msg);
12 }
13
14 public ServiceException(Exception e){
15 super("service层异常",e);
16 }
17
18 public ServiceException(String msg , Exception e){
19 super(msg,e);
20 }
21 }
 1 package com.wei.service.impl;
2
3 // class created by wwei 2011-12-11 下午02:16:59
4
5 public class ServiceImpl {
6
7 DaoImpl daoImpl = new DaoImpl();
8
9 public void testServiceExce(int num) throws ServiceException{
10 try {
11 int a = 2/num; //参数num若为0,报异常java.lang.ArithmeticException: / by zero
12 } catch (Exception e) {
13 throw new ServiceException("num为零,零不能做除数!",e);
14 }
15 daoImpl.testDaoExce();
16 }
17 }
 1 package com.wei.test;
2
3 // class created by wwei 2011-12-11 下午01:32:45
4
5 public class Test {
6 public static void main(String[] args) {
7 ServiceImpl service = new ServiceImpl();
8 try {
9 int num = 0;
10 service.testServiceExce(num);
11 } catch (Exception e) {
12 e.printStackTrace();
13 }
14 }
15 }

当num为0时,报的是Service层的错。

com.wei.test.ServiceException: num为零,零不能做除数!
at com.wei.test.ServiceImpl.testServiceExce(ServiceImpl.java:13)
at com.wei.test.Test.main(Test.java:10)
Caused by: java.lang.ArithmeticException: / by zero
at com.wei.test.ServiceImpl.testServiceExce(ServiceImpl.java:11)
... 1 more

当num不为0时,报的是dao层的错

com.wei.test.DaoException: dao层testDaoExce方法异常
at com.wei.test.DaoImpl.testDaoExce(DaoImpl.java:11)
at com.wei.test.ServiceImpl.testServiceExce(ServiceImpl.java:15)
at com.wei.test.Test.main(Test.java:10)
Caused by: java.lang.NullPointerException
at com.wei.test.DaoImpl.testDaoExce(DaoImpl.java:9)
... 2 more









 

原文地址:https://www.cnblogs.com/csuwangwei/p/2283935.html