---
title: "9.58 正确的使用异常"
author: "bingooh"
date: "2013-08-18T20:13:45Z"
tags: []
categories: ["编程语言"]
slug: "9-58"
draft: false
lastmod: "2013-08-18T20:13:45Z"
id: 1924976
url: "https://bingooh.iteye.com/blog/1924976"
---

Java的异常包括checked exception和unchecked exception，后者又包括runtime exception和error。使用基本原则包括：

1.如果异常是可恢复的，那么应使用checked exception。调用者必须使用try/catch捕获checked exception并处理（如果捕获那么编译时会提示错误）

 

2.如果异常是不可恢复的，那么应使用unchecked exception。其中runtime exception用于表示编程错误，error表示系统错误

 

3.自定义checked exception应继承Exception类，自定义unchecked exception应继承RuntimeException类。建议不要继承Error类，因为系统如果抛出error，一般会终止运行

 

4.自定义异常类可以提供相关方法获取触发异常的原因