java exception 定义_Java如何定义自己的exception

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;

}

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值