异常处理
来源:互联网 发布:倒计时软件哪个好桌面 编辑:程序博客网 时间:2024/05/18 00:12
1.异常(例外、差错):exception
基本写法:
try{ 语句组 }catch(Exception ex){ 异常处理语句; }
例:
import java.io.*;public class Test { public static void main(String[] args) { try{ BufferedReader in = new BufferedReader( new InputStreamReader( System.in ) ); System.out.print("Please input a number: "); String s = in.readLine(); int n = Integer.parseInt( s ); }catch(IOException ex){ ex.printStackTrace(); }catch(NumberFormatException ex){ ex.printStackTrace(); } }}
2.Java中的异常处理
(1)抛出(throw)异常
throw 异常对象;
(2)运行时系统在调用栈中查找
(3)捕获(catch)异常的代码
try{ 语句组; }catch(异常类名,异常形式参数名){ 异常处理语句组; }finally{ 异常处理语句组; }
3.异常的分类
Throwable
(1)Error:JVM的错误
(2)Exception:异常
Exception类:
构造方法:
public Exception();public Exception(String message);Exception(String message, Throwable cause);
方法:
getMessage()getCause()printStackTrace()
4.多异常处理
子类异常要排在父类异常的前面
finally语句
无论是否有异常都要执行
例:
public class Test { public static String output = ""; public static void foo(int i) { try{ if(i == 1) { throw new Exception(); } output += "1"; } catch(Exception e) { output +="2"; return; } finally { output +="3"; } output += "4"; } public static void main(String[] args) { foo(1);//23 foo(0);//134 System.out.println(output); }}
5.受检的异常
Exception分两种
(1)RuntimeException及其子类
(2)受检的异常(checked Exception)
受检的异常:
(1)catch
(2)throws
阅读全文
0 0
- 异常处理+异常+处理异常+自定义异常
- 异常处理
- 异常处理
- 异常处理
- 异常处理
- 异常处理
- 异常处理
- 异常处理
- 异常处理
- 异常处理
- 异常处理
- 异常处理
- 异常处理
- 异常处理
- 异常处理
- 异常处理
- 异常处理
- 异常处理
- 【练习作业】HBase与Hive操作
- Sigmetrix.GD&T.Advisor.V2.3.1.For.Creo.1.0-3.0 CETOL.v8.1.for.WILDFIRE2.0-3.0 Proe公差分析软件
- @ResrController与@Controller的区别
- 482. License Key Formatting
- phpcms 常用类
- 异常处理
- Python(7)实现一个简单的购物车逻辑
- 实验二 Linux 用户管理
- 用HTML5自制视频控件
- 程序是怎么跑起来的(3)---计算机进行小数运算时出错的原因
- Eclipse中Maven工程缺少Maven Dependencies
- angular-ng new
- 贪心算法:喷水装置(一)
- PAT 1013. Battle Over Cities (25)