Java面向对象程序设计第八章

本文通过Java代码示例介绍了异常处理的基本用法,包括如何捕获ArrayIndexOutOfBoundsException和NullPointerException等异常,并展示了如何使用System.in进行输入流读取。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

异常处理

import java.util.Scanner;

public class hello {
	
	public static void f()
	{
		int[] a = new int[10];
		a[10] = 10;
		System.out.println("hello");
	}

	public static void g()
	{
		f();
	}
	
	public static void h()
	{
		int i = 10;
		if( i < 100 )
		{
			g();
		}
	}
	
	public static void k()
	{
		try
		{
			h();
		}catch( NullPointerException e)
		{
			System.out.println("k() caught");
		}
	}
	
	public static void main(String[] args) {
		try 
		{
			k();
		} catch( ArrayIndexOutOfBoundsException e )
		{
			System.out.println("caught");
			System.out.println(e.getMessage());
			System.out.println("----------");
			System.out.println(e);
			System.out.println("----------");
			e.printStackTrace();
		}
		System.out.println("main");
	}
}

输入流

import java.io.IOException;
import java.util.Scanner;

public class hello {

	public static void main(String[] args) {
		System.out.println("hello world");
		byte[] buffer = new byte[1024]; // 8bit
		try {
			int len = System.in.read(buffer);
			String s = new String(buffer, 0, len);
			System.out.println("读到了" + len + "字节");
			System.out.println(s);
			System.out.println("s的长度" + s.length());

		} catch (IOException e) {
			e.printStackTrace();
		}
	}
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值