⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 throwtest.java

📁 本java源程序包括了大量的学习程序(共27章)方便大家学习
💻 JAVA
字号:
import java.io.*;
class ThrowTest
{
	//定义throwTest1()方法,并抛出ArithmeticException异常
	public void throwTest1() throws ArithmeticException
	{
		//方法中输出3/0的值,会出现异常
		System.out.println(3/0);
	}
    //定义throwTest2()方法,并抛出ArrayIndexOutOfBoundsException异常
	public void throwTest2() throws ArrayIndexOutOfBoundsException
	{
		int a[] = {1,2};
		//方法中输出数组a[2]的值,由于数组只包含a[0]=1,a[1]=2两个元素,所以出现异常
		System.out.println(a[2]);
	}
    //定义throwTest3()方法,并抛出FileNotFoundException异常
	public void throwTest3() throws FileNotFoundException
	{
		File file = new File("abc.txt");
		//方法中打开文件使用BufferedReader类打开文件,由于文件不存在出现异常
		new BufferedReader(new FileReader(file));
	}
    //定义throwTest4()方法,并抛出FileNotFoundException异常
	public void throwTest4() throws FileNotFoundException
	{
		//直接用throw语句抛出FileNotFoundException异常
		throw new FileNotFoundException("abc.txt");
	}	
	public static void main(String argv[])
	{
		ThrowTest throwTest = new ThrowTest();
		//调用抛出算术异常的方法throwTest1(),并捕获处理异常
		try             //检查是否出现异常
		{
			throwTest.throwTest1();  
		}
		catch(ArithmeticException e1)   //捕捉异常
		{
	    	System.out.print("3/0: " );
	    	System.out.println("This is ArithmeticException");
		}
        //调用抛出数组越界异常的方法throwTest2(),并捕获处理异常
		try     //检查是否出现异常
		{
			throwTest.throwTest2();
		}
		catch(ArrayIndexOutOfBoundsException e2)  //捕捉异常
		{
	    	System.out.print("a[2] is out of Array: " );
	    	System.out.println("This is ArrayIndexOutOfBoundsException");
		}
		//调用抛出I/O异常的方法throwTest3(),并捕获处理异常
		try    //检查是否出现异常
		{
			throwTest.throwTest3();
		}
		catch(FileNotFoundException e3)   //捕捉异常
		{
	    	System.out.print("abc.txt is not found: " );
	    	System.out.println("This is FileNotFoundException");
		}
        //调用抛出I/O异常的方法throwTest4(),并捕获处理异常
		try    //检查是否出现异常
		{
			throwTest.throwTest4();
		}
		catch(FileNotFoundException e4)    //捕捉异常
		{
	    	System.out.print("abc.txt is not found: " );
	    	System.out.println("This is FileNotFoundException");
		}
	}
}

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -