Java如何定义自己的exception
2009-05-15 12:16
363 查看
import java.io.*;
// A Java application to demonstrate making your own Exception class // This program catches the exception when the word "client" is // entered incorrectly.
public class TestException { static String s = "";
//-------------------------------------------------------- public static void main (String args[]) { InputStreamReader is = new InputStreamReader(System.in); BufferedReader buf = new BufferedReader(is); System.out.println("Enter the word you cannot spell: "); try { s = buf.readLine(); } catch (IOException e) { System.out.println("IOException was " + e.getMessage()); }
try { checkSpelling(); // this method throws SpellException } catch (SpellException se) // but it is caught here { System.out.println("Spell exception was: " + se.getError()); } } // end main
//---------------------------------------------------------- // Check spelling of typed in word. Throw exception if wrong. // Note how this method specifies that it throws such and such // exception. Does not have to be caught here.
private static void checkSpelling() throws SpellException { if (s.equalsIgnoreCase("client")) System.out.println("OK"); else throw new SpellException("Cannot spell client"); }
} // end main class
//*********************************************** // Custom exception class that descends from Java's Exception class.
class SpellException extends Exception { String mistake;
//---------------------------------------------- // Default constructor - initializes instance variable to unknown
public SpellException() { super(); // call superclass constructor mistake = "unknown"; }
//----------------------------------------------- // Constructor receives some kind of message that is saved in an instance variable.
public SpellException(String err) { super(err); // call super class constructor mistake = err; // save message }
//------------------------------------------------ // public method, callable by exception catcher. It returns the error message.
public String getError() { return mistake; } }
相关文章推荐
- JAVA架构师必知之事 —— 如何定义自己的职业路线?
- 如何结合Sping与Java封装自己的Exception?
- java如何定义自己的类
- 如何在Java中定义常量(Constant)
- Java深入 - 深入 Java自己定义注解
- 如何定义自己的ViewGroup
- 如何在Cruise中显示自己定义的report (将EMMA的report显示在页面上)
- 记录:java执行mysql语句查询字段类型:timestamp返回页面显示会多出个 .0,自己如何处理的
- 4-1 如何定义 Java 中的方法;Java 中无参无返回值方法的使用;Java 中无参带返回值方法的使用;
- 在xml中如何引用自己定义的schema文件?
- 关于自己定义的多类型输入框,如何配合软键盘的显示
- 如何理解 Java 之父 James Gosling 对 Java 的定义?
- ubuntu下自己写一个在某package文件下的HelloWorld.java如何执行
- Rails框架技术讲座:如何定义自己的Rails应用软件入门位置
- 如何在Java中定义常量(Constant)
- 如何提高自己的 Java 编程技能
- 如何定义自己的控件
- java 将一个字符串解析为日期 将日期转为自己定义的格式以字符串输出
- Java程序员该如何提升让自己成为高薪架构师?
- Java中如何使封装自己的类,建立并使用自己的类库?