The following code creates a new subclass of Exception.
It then uses that subclass to signal an error condition in a method.
It overrides the toString()
method to provide a description of the exception.
class MyException extends Exception { private int detail; public MyException(int a) { detail = a; /*from w w w . j a v a 2 s. com*/ } public String toString() { return "MyException[ value is " + detail + "]"; } } public class Main { static void compute(int a) throws MyException { throw new MyException(a); } public static void main(String args[]) { try { compute(1); compute(20); } catch (MyException e) { System.out.println("Caught " + e); } } }
public class Main { static Object chatServer = null; public static void main(String[] args) { try {/* w ww . ja va 2 s.com*/ sendChat("Hello, how are you?"); } catch (ConnectionUnavailableException e) { System.out.println("Got a connection unavailable Exception!"); } disconnectChatServer(chatServer); } private static void disconnectChatServer(Object chatServer) { if (chatServer == null) throw new IllegalChatServerException("Chat server is empty"); } private static void sendChat(String chatMessage) throws ConnectionUnavailableException { if (chatServer == null) throw new ConnectionUnavailableException("Can't find the chat server"); } } class ConnectionUnavailableException extends Exception { ConnectionUnavailableException(String message) { super(message); } } class IllegalChatServerException extends RuntimeException { IllegalChatServerException(String message) { super(message); } }