public class Test {
public static void main(String[] args) {
int userInput=0;
int I = 6 / userInput;
System.out.println("优雅结束");
}
}
输出结果:
Exception in thread "main" java.lang.ArithmeticException: / by zero
at Test.main(Test.java:4)
public class Test {
public static void main(String[] args) {
try
{
int userInput=0;
int I = 6 / userInput;
}
/*系统把错误信息放在Exception的对象e中*/
catch(Exception e)
{
System.out.println(e);
}
System.out.println("优雅结束");
}
}
我怎么知道应该捕获什么样的异常?
如上例:开始没加try时,程序崩溃,系统打印的是如下的错误,Exception in thread "main" java.lang.ArithmeticException: / by zero at Test.main(Test.java:4), 所以我们就该捕获ArithmeticException.见下例。
public class Test {
public static void main(String[] args) {
try
{
int userInput=0;
int I = 6 / userInput;
}
catch(ArithmeticException e)
{
System.out.println(e);
}
System.out.println("优雅结束");
}
}
public class Test {
/* maxMemory将返回java虚拟机所能返回的最大可用内存。0.92可以, 0.93就报错 */
int size win = (int) (Runtime.getRuntime().maxMemory() * 0.93);
public void allo() {
byte[] data1 = new byte[win];
}
public static void main(String[] args) {
Test t = new Test();
t.allo();
}
}
输出结果:
Exception in thread "main" java.lang.OutOfMemoryError: Java heap space
at Test.allo(Test.java:5)
at Test.main(Test.java:9)作者: itheima_llt 时间: 2015-4-21 20:48
知道了 不错~~~作者: Zack 时间: 2015-4-22 11:49