自定义异常在抛出的时候才会被捕获到 只有捕获到异常才会执行相应的代码 比如 class MyException extends Exception { public MyException(String s) { super(s); } }class ExceptionHander { public void throwsException() throws MyException { throw new MyException("自定义异常"); } }public class Test { /** * @param args */ public static void main(String[] args) { // TODO Auto-generated method stub ExceptionHander ex = new ExceptionHander(); try { ex.throwsException(); } catch (MyException e) { // TODO Auto-generated catch block e.printStackTrace(); } }}
希望这个代码对你有帮助。 package com.walkman.august.weektwo; /** * @title 一个自定义异常的例子 * @author walkman * */ public class SelfExceptionTest { public static void main(String[] args) { // TODO Auto-generated method stub int a; int b; int c;
static void makeException(int a) throws ExceptionOne, ExceptionTwo{ if(a < 10) { throw new ExceptionOne(a); } if(a > 10) { throw new ExceptionTwo(a); } System.out.println("when a is " + a + " No exception"); }}class ExceptionOne extends Exception { int num;
ExceptionOne(int a) { num = a; }
public String toString() { return num + "<10!值必须大于10"; } }class ExceptionTwo extends Exception { int num;
ExceptionTwo(int a) { num = a; }
public String toString() { return num + ">10!值必须小于10"; } }
只有捕获到异常才会执行相应的代码
比如
class MyException extends Exception {
public MyException(String s) {
super(s);
}
}class ExceptionHander {
public void throwsException() throws MyException {
throw new MyException("自定义异常");
}
}public class Test { /**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
ExceptionHander ex = new ExceptionHander();
try {
ex.throwsException();
} catch (MyException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}}
package com.walkman.august.weektwo;
/**
* @title 一个自定义异常的例子
* @author walkman
*
*/
public class SelfExceptionTest { public static void main(String[] args) {
// TODO Auto-generated method stub
int a;
int b;
int c;
a = Integer.parseInt("10");
b = Integer.parseInt("12");
c = Integer.parseInt("8");
try {
makeException(a);
makeException(b);
makeException(c);
} catch (ExceptionOne e) {
System.out.println(" " + e);
} catch (ExceptionTwo e) {
System.out.println(" " + e);
}
}
static void makeException(int a) throws ExceptionOne, ExceptionTwo{
if(a < 10) {
throw new ExceptionOne(a);
}
if(a > 10) {
throw new ExceptionTwo(a);
}
System.out.println("when a is " + a + " No exception");
}}class ExceptionOne extends Exception
{
int num;
ExceptionOne(int a) {
num = a;
}
public String toString() {
return num + "<10!值必须大于10";
}
}class ExceptionTwo extends Exception
{
int num;
ExceptionTwo(int a) {
num = a;
}
public String toString() {
return num + ">10!值必须小于10";
}
}