Java异常处理机制(二)

2015-07-16 12:55:00 · 作者: · 浏览: 20
{
? ? ? ? ? ? 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.