常见的有:数组越界,除数与被除数是0…
object 是所有类的直接或间接父类
Throwable类
分为Exception,error
error错误一般无法处理,需要程序员来处理,属于严重问题
Exception分为
运行时异常,runtime
非运行时异常,编译期的问题
- 抛出异常具体信息
- 停止程序的运行
Exception in thread “main” java.lang.ArrayIndexOutOfBoundsException: 3
at TempAndTest.test1.main(test1.java:6)
Exception in thread “main” :异常所在线程
java.lang.ArrayIndexOutOfBoundsException: 3:异常的类型
at TempAndTest.test1.main(test1.java:6): 异常所在位置
package TempAndTest;
public class test1 {
public static void main(String[] args) {
int[]arry=new int[3];
try {
for (int i=0;i<4;i++)
{
System.out.println(arry[i]);
}
}
catch (ArrayIndexOutOfBoundsException e)
{
// 抓到数组越界的异常,咱不去处理,程序依旧可以执行
}
catch (Exception e)
{
// catch只执行第一个抓到的catch
System.out.println("虽然数组发生越界,但是并不影响程序继续执行,增强程序的健壮性");
}
finally {
System.out.println("程序继续跑,不会因为异常而停止");
}
}
}
Throwable成员方法
花式打印错误信息
catch (ArrayIndexOutOfBoundsException e)
{
System.out.println(e.getMessage());
System.out.println(e.toString());
e.printStackTrace();
}
Throws异常
throw异常其实并没有处理异常
package TempAndTest;
public class test1 {
public static void main(String[] args) {
try {
System.out.println("throws本质就是对异常进行延后处理");
// 需要继续在处理
function();
System.out.println("如果不进行操作,则同样,遇到异常就停止");
} catch (ArrayIndexOutOfBoundsException e) {
} finally {
System.out.println("在主函数中处理function中抛的异常");
}
}
// 只是把异常抛出到调用函数上,并不是
public static void function ()throws ArrayIndexOutOfBoundsException
{
System.out.println("这里只是把异常抛出到上一层,并不会对异常进行处理");
int []arry=new int[1];
System.out.println(arry[1]);
}
}
自定义异常
可以通过继承runtimeexception或者exception来自定义异常类
package TempAndTest;
public class test1 {
public static void main(String[] args) throws myException{
try {
// 咱在main中直接抛出异常
// 也可以做判断,是否throw异常
throw new myException("这是异常提示信息");
}
catch (myException e)
{
e.printStackTrace();
}
System.out.println("嗨嗨嗨!");
}
}
// 通过继承exception和RuntimeException实现自定义异常类
class myException extends Exception
{
// 异常类的构造
myException()
{}
myException(String s)
{
// 调用父类的构造
super(s);
}
}



