在Java编程中,如何创建用户自定义异常?
此示例显示如何通过扩展Exception
类来创建用户定义的异常。
package com.yiibai;
class MyException extends Exception { String s1; MyException(String s2) { s1 = s2; } @Override public String toString() { return ("Output String = " + s1); } } public class UserDefinedException { public static void main(String args[]) { try { throw new MyException("Custom message"); } catch (MyException exp) { System.out.println(exp); } } }
上述代码示例将产生以下结果 -
Output String = Custom message