Java中关于异常的一些问题(三)
2016-04-16 13:57
495 查看
使用throws声明抛出 的异常
格式如下:
throws ExceptionClass1,ExceptionClass2...
使用throws声明抛出异常时有一个限制:子类方法声明抛出的异常类型应该是父类方法声明抛出的异常类型的子类或相同,子类方法声明抛出的异常不允许比父类方法声明抛出的异常多。
使用throw抛出异常
格式:
throw ExceptionInstance;
public class ThrowTest
{
public static void main(String[] args)
{
try
{
// 调用声明抛出Checked异常的方法,要么显式捕获该异常
// 要么在main方法中再次声明抛出
throwChecked(-3);
}
catch (Exception e)
{
System.out.println(e.getMessage());
}
// 调用声明抛出Runtime异常的方法既可以显式捕获该异常,
// 也可不理会该异常
throwRuntime(3);
}
public static void throwChecked(int a)throws Exception
{
if (a > 0)
{
// 自行抛出Exception异常
// 该代码必须处于try块里,或处于带throws声明的方法中
throw new Exception("a的值大于0,不符合要求");
}
}
public static void throwRuntime(int a)
{
if (a > 0)
{
// 自行抛出RuntimeException异常,既可以显式捕获该异常
// 也可完全不理会该异常,把该异常交给该方法调用者处理
throw new RuntimeException("a的值大于0,不符合要求");
}
}
}
总结:
1、不要过度使用异常
2、不要使用过于庞大的try块
3、避免使用Catch All语句
4、不要忽略捕获到的异常
格式如下:
throws ExceptionClass1,ExceptionClass2...
使用throws声明抛出异常时有一个限制:子类方法声明抛出的异常类型应该是父类方法声明抛出的异常类型的子类或相同,子类方法声明抛出的异常不允许比父类方法声明抛出的异常多。
import java.io.*; public class OverrideThrows { public void test()throws IOException { FileInputStream fis = new FileInputStream("a.txt"); } } class Sub extends OverrideThrows { // 子类方法声明抛出了比父类方法更大的异常 // 所以下面方法出错 public void test()throws Exception { } }上面程序中Sub子类中的test()方法声明抛出Exception,该Exception是其父类声明抛出异常IOException类的父类,这将导致程序无法通过编译。
使用throw抛出异常
格式:
throw ExceptionInstance;
public class ThrowTest
{
public static void main(String[] args)
{
try
{
// 调用声明抛出Checked异常的方法,要么显式捕获该异常
// 要么在main方法中再次声明抛出
throwChecked(-3);
}
catch (Exception e)
{
System.out.println(e.getMessage());
}
// 调用声明抛出Runtime异常的方法既可以显式捕获该异常,
// 也可不理会该异常
throwRuntime(3);
}
public static void throwChecked(int a)throws Exception
{
if (a > 0)
{
// 自行抛出Exception异常
// 该代码必须处于try块里,或处于带throws声明的方法中
throw new Exception("a的值大于0,不符合要求");
}
}
public static void throwRuntime(int a)
{
if (a > 0)
{
// 自行抛出RuntimeException异常,既可以显式捕获该异常
// 也可完全不理会该异常,把该异常交给该方法调用者处理
throw new RuntimeException("a的值大于0,不符合要求");
}
}
}
总结:
1、不要过度使用异常
2、不要使用过于庞大的try块
3、避免使用Catch All语句
4、不要忽略捕获到的异常
相关文章推荐
- 给Eclipse提速的7个技巧
- Java中基本类型
- Spring@Autowired注解与自动装配
- [学习笔记]Java正则表达式
- java中使用频繁的Arrays类成员方法
- java中使用频繁的Arrays类成员方法
- [学习笔记]Java IO之其他流及总结
- [学习笔记]Java IO之字符流
- Java标识符
- [学习笔记]Java IO之文件
- [学习笔记]Java IO之字节流
- [学习笔记]Java日期类及其处理
- [学习笔记]Java常用工具类
- Eclipse_Java编码规范详细设置
- java入门
- [学习笔记]Java集合框架之Map集合
- SpringMVC表单标签简介
- [学习笔记]Java集合框架之Set集合
- [学习笔记]Java基本数据类型包装类
- [学习笔记]Java多线程经典问题