---
title: "Java 自定义异常类"
author: "何不笑"
date: "2013-02-22T10:58:52Z"
tags: []
categories: ["编程语言"]
slug: "java"
draft: false
lastmod: "2013-02-22T11:00:18Z"
id: 1812326
url: "https://wait7758521.iteye.com/blog/1812326"
---

```
public class ExceptionTest {
	public static void main(String [] args){
		int result;
		Test test = new Test();
		try{
			//result = test.devide(10, 0);
			result = test.devide(10, -2);
			//result = test.devide(10, 2);
			
		}catch (DevidedByMinusException e) {
			System.out.println(e.getMessage()+"; the devisor is "+e.getDevisor());
		}catch (ArithmeticException e) {
			System.out.println(e.getMessage());
		}catch (Exception e) {
			System.out.println(e.getMessage());
		}finally{
			System.out.println("finally");
		}
		System.out.println("The program is running here, that is normal!");
	}
}

class DevidedByMinusException extends Exception{
	int devisor;
	public DevidedByMinusException(String msg, int divisor){
		super(msg);
		this.devisor = devisor;
	}
	
	public int getDevisor() {
		return devisor;
	}
}

class Test{
	public int devide(int x, int y) throws ArithmeticException, DevidedByMinusException{
		if(y < 0){
			throw new DevidedByMinusException("被除数为负", y);
		}
		return x/y;
	}
}
```

   
![](http://dl.iteye.com/upload/attachment/0080/7285/d9ad374d-e28e-3f99-9b65-78992dff6ecb.png)  
 

   
![](http://dl.iteye.com/upload/attachment/0080/7287/5c9ff282-a43c-325b-9419-4c964ab27c2b.png)  
 

选自《Java 就业培训教程》