Java异常

一、Java的异常结构图:

error是系统的问题,程序员无法处理。

exception是程序员可以处理的异常:分为

1、RuntimeException:运行时异常,可以处理也可以不处理

2、左边的,必须处理。

二、

原则:1、先catch子异常,后catch大的异常

    2、重写的方法要么和原方法抛出相同的异常,要么不抛出异常

三、代码简单解释

/**
*异常处理
*try throws throw catch finally
*/
import java.io.*;
public class TestEx
{
	public static void main(String[] args)
	{
		int[] arr = {1,2,3};
		try
		{
			System.out.println(arr[4]);//数组越界
		}
		catch (ArrayIndexOutOfBoundsException xx)
		{
			System.out.println("打印堆栈信息如下:\n");
			xx.printStackTrace();
		}
		finally//可以用于执行资源清理工作,如:关闭打开的文件、删除临时文件
		{
			System.out.println("我一定会被执行");
		}
		
		/**************************************************/
		
		FileInputStream in = null;
		try
		{
			in = new FileInputStream("myfile.txt");
			int b;
			b = in.read();
			while (b != -1)
			{
				System.out.print((char) b);
				b = in.read();
			}
		}
		catch (FileNotFoundException a)
		{
			a.printStackTrace();
		}
		catch (IOException b)
		{
			System.out.println(b.getMessage());
		}
		finally
		{
			try
			{
				in.close();
			}
			catch (IOException a)
			{
				a.printStackTrace();
			}
		}
	}
	
	/********************************************/
		
		void m(int i) throws ArithmeticException
		{
			if(i == 0)
			{
				throw new ArithmeticException("被除数为0");
			}
		}
		
		/********************************************/
		//处理不了的异常可以向更高级抛出
		
		void f() throws FileNotFoundException,IOException
		{
			FileInputStream in = new FileInputStream("myfile.txt");
			int b;
			b = in.read();
			
			while (b != -1)
			{
				System.out.print(b);
				b =in.read();
			}
		}
		
		void f2()
		{
			try 
			{
				f();
			}
			catch(FileNotFoundException e)
			{
				e.printStackTrace();
			}
			catch (IOException e)
			{
				e.printStackTrace();
			}
		}
}

/**
*自定义异常
*/
class MyException extends Exception
{
	private int id;
	public MyException(String message,int id )
	{
		super(message);
		this.id = id ;
	}
	public int getId()
	{
		return id;
	}
}

public class Test
{
	public void regist(int num) throws MyException
	{
		if (num<0)
		{
			throw new MyException("人数为负值,不合理",4);
		}
		System.out.println("登记人数"+num);
	}
	
	public void manager()
	{
		try
		{
			regist(-1);
		}
		catch(MyException e)
		{
			System.out.println("等级失败,类型码为:"+e.getId());
			e.printStackTrace();
		}
		System.out.println("操作结束");
	}
	
	public static void main(String[] args)
	{
		Test t = new Test();
		t.manager();
	}
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值