异常处理
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();
}
}
}
本文通过Java代码示例介绍了异常处理的基本用法,包括如何捕获ArrayIndexOutOfBoundsException和NullPointerException等异常,并展示了如何使用System.in进行输入流读取。
657

被折叠的 条评论
为什么被折叠?



