public class TestException {
public static void main(String[] args) {
int c = 0;
try
{
int a = 3;
int b = 0;
// 这块代码出现了异常
c = a / b;
// 那么异常之后的代码都不会被执行
System.out.println("Hello World");
}
catch (ArithmeticException e)
{
System.out.println("除数不能为零");
}
finally
{
//不管有没有发生异常,finally语句块都会被执行
System.out.println("Welcome");
}
System.out.println(c);
// 当b为0时,有异常,输出为c的初始值0
}
}
//输出结果:除数不能为零 Welcome 0
try异常
import java.io.FileInputStream;
import java.io.FileNotFoundException;
public class DemoException {
public static void main(String[] args) {
int a=test3();
System.out.println(a);
}
@SuppressWarnings("finally")
public static int test3(){
try {
System.out.println(9 / 0);
return 1;
} catch (Exception e) {
System.out.println("捕获到了异常....");
return 2;
}finally{
System.out.println("无论如何都会执行的代码...");
return 3;
}
}
}
//输出结果 "呵呵""哈哈" 3
带有return异常
//throws在方法体头部通过声明 抛出异常...
public void dealFile() throws FileNotFoundException{
FileInputStream fis =new FileInputStream("C:/name.txt");
}
//那么那么上面调用这个方法可以选择是继续抛出,还是捕获异常
public class TestException {
public static void main(String[] args) {
try {
Test3(); //这里选择直接捕获异常,而不是在抛出异常
} catch (NumberFormatException e) {
System.err.println("非数据类型不能转换。");
} //System.err.println();这种输出方式可以输出错误的消息,在控制台呈现红色。
}
public static void Test3() throws NumberFormatException{
String s = "abc";
System.out.println(Double.parseDouble(s));
}
}
throws异常
public class TestException {
public static void main(String[] args) {
String s = "abc";
if(s.equals("abc")) {
throw new NumberFormatException("不能相等");
} else {
System.out.println(s);
}
}
}
throw异常
public class MyException extends Exception
{
public MyException()
{
super();
}
public MyException(String message)
{
super(message);
}
}
public class ExceptionTest4
{
public void method(String str) throws MyException
{
if(null == str)
{
throw new MyException("传入的字符串参数不能为null!");
}
else
{
System.out.println(str);
}
}
public static void main(String[] args) throws MyException //异常处理方式1,不断向外抛出
{
ExceptionTest4 test = new ExceptionTest4();
test.method(null);
}
}
public class ExceptionTest4
{
public void method(String str) throws MyException
{
if (null == str)
{
throw new MyException("传入的字符串参数不能为null!");
}
else
{
System.out.println(str);
}
}
public static void main(String[] args)
{
//异常处理方式2,采用try...catch语句
try
{
ExceptionTest4 test = new ExceptionTest4();
test.method(null);
}
catch (MyException e)
{
e.printStackTrace();
}
finally
{
System.out.println("程序处理完毕");
}
}
}
机械节能产品生产企业官网模板...
大气智能家居家具装修装饰类企业通用网站模板...
礼品公司网站模板
宽屏简约大气婚纱摄影影楼模板...
蓝白WAP手机综合医院类整站源码(独立后台)...苏ICP备2024110244号-2 苏公网安备32050702011978号 增值电信业务经营许可证编号:苏B2-20251499 | Copyright 2018 - 2025 源码网商城 (www.ymwmall.com) 版权所有