class MyException extends Exception
{
private int id;
MyException()
{
System.out.println("我是自定义异常");
}
MyException(String msg,int id)
{
super(msg);
this.id = id;
}
void method() throws MyException
{
if(id == 1)
throw new MyException();
}
}
public class TestException
{
public static void main(String[] args)
{
int a = 10;
//System.out.println(a/0);
/*
Exception in thread "main" java.lang.ArithmeticException: / by zero
at TestException.main(TestException.java:6)
*/
try
{
System.out.println(a/0);
}
catch (ArithmeticException ae)
{
//ae.printStackTrace();
/*
java.lang.ArithmeticException: / by zero
at TestException.main(TestException.java:13)
*/
//System.out.println(ae.getMessage());
}
MyException me = new MyException("my1",1);
try
{
me.method();
}
catch (MyException m)
{
//m.printStackTrace();
/*
我是自定义异常
MyException
at MyException.method(TestException.java:16)
at TestException.main(TestException.java:45)
*/
System.out.println(m.getMessage());
}
}
}
/*
总结:
1.异常:编译时无错,只有运行时,才会抛出异常
RuntimeException可以不处理,其他的Exception必须捕获处理
2.异常类的常见方法:
1)getMessage 返回值:String
2)printStackTrace 返回值:void
3.自定义异常
4.异常的1图5个关键字
1图:Throwable类下面分Error类和Exception类
Exception类又分RuntimeException类
5个关键字:try,catch,finally,throw和throws
*/
{
private int id;
MyException()
{
System.out.println("我是自定义异常");
}
MyException(String msg,int id)
{
super(msg);
this.id = id;
}
void method() throws MyException
{
if(id == 1)
throw new MyException();
}
}
public class TestException
{
public static void main(String[] args)
{
int a = 10;
//System.out.println(a/0);
/*
Exception in thread "main" java.lang.ArithmeticException: / by zero
at TestException.main(TestException.java:6)
*/
try
{
System.out.println(a/0);
}
catch (ArithmeticException ae)
{
//ae.printStackTrace();
/*
java.lang.ArithmeticException: / by zero
at TestException.main(TestException.java:13)
*/
//System.out.println(ae.getMessage());
}
MyException me = new MyException("my1",1);
try
{
me.method();
}
catch (MyException m)
{
//m.printStackTrace();
/*
我是自定义异常
MyException
at MyException.method(TestException.java:16)
at TestException.main(TestException.java:45)
*/
System.out.println(m.getMessage());
}
}
}
/*
总结:
1.异常:编译时无错,只有运行时,才会抛出异常
RuntimeException可以不处理,其他的Exception必须捕获处理
2.异常类的常见方法:
1)getMessage 返回值:String
2)printStackTrace 返回值:void
3.自定义异常
4.异常的1图5个关键字
1图:Throwable类下面分Error类和Exception类
Exception类又分RuntimeException类
5个关键字:try,catch,finally,throw和throws
*/