设为首页 加入收藏

TOP

Java异常处理机制(二)
2015-07-16 12:55:00 来源: 作者: 【 】 浏览:7
Tags:Java 异常 处理 机制
{
? ? ? ? ? ? char c=str.charAt(0);
? ? ? ? ? ? if(c<'a'||c>'z'||c<'A'||c>'Z')
? ? ? ? ? ? ? ? throw new FirstLetterException();
? ? ? ? }
? ? ? ? catch (FirstLetterException e)
? ? ? ? {
? ? ? ? ? ? System.out.println("This is FirstLetterException");
? ? ? ? }


? ? }


}


class FirstLetterException extends Exception{
? ? public FirstLetterException()
? ? {
? ? ? ? super("The first char is not a letter");
? ? }
? ?
? ? public FirstLetterException(String str)
? ? {
? ? ? ? super(str);
? ? }
}


This is FirstLetterException


public class MyException {


? ? public static void main(String[] args) throws FirstLetterException{
? ? ? ? throw new FirstLetterException();
? ? }
}


class FirstLetterException extends Exception{
? ? public FirstLetterException()
? ? {
? ? ? ? super("The first char is not a letter");
? ? }
? ?
? ? public FirstLetterException(String str)
? ? {
? ? ? ? super(str);
? ? }
}


Exception in thread "main" FirstLetterException: The first char is not a letter
?at MyException.main(MyException.java:5)


4. 使用finally语句


在使用try...catch语句是,若try语句中的某一句出现异常情况,那么这部分try语句段中,从出现异常的语句开始,之后的所有语句都不会被执行,直到这部分try语句段结束。


但是在很多情况下,希望无论是否出现异常,某些语句都需要被执行。那么就可以把这部分代码放在finally语句段中,即使try或catch语句段中含有return语句,程序都会在异常抛出后先执行finally语句段,除非try或catch语句段中执行System.exit()方法,或者是出现Error错误,finally语句才不会被执行而退出程序。


import java.io.*;


public class FinallyTest {


? ? public static void main(String[] args) {
? ? ? ? File file=null;
? ? ? ? BufferedReader input=null;
? ? ? ? file=new File("abc.txt");
? ? ? ?
? ? ? ? try
? ? ? ? {
? ? ? ? ? ? input=new BufferedReader(new FileReader(file));
? ? ? ? }
? ? ? ? catch(FileNotFoundException e)
? ? ? ? {
? ? ? ? ? ? System.out.print("abc.txt is not found: ");
? ? ? ? ? ? System.out.println("This is FileNotFoundException");
? ? ? ? }
? ? ? ? finally
? ? ? ? {
? ? ? ? ? ? System.out.println("This is finally code part.");
? ? ? ? }


? ? }


}


abc.txt is not found: This is FileNotFoundException
This is finally code part.


首页 上一页 1 2 下一页 尾页 2/2/2
】【打印繁体】【投稿】【收藏】 【推荐】【举报】【评论】 【关闭】 【返回顶部
分享到: 
上一篇Java的堆(Heap)和栈(Stack)的.. 下一篇Android利用canvas画画板

评论

帐  号: 密码: (新用户注册)
验 证 码:
表  情:
内  容: