java abnormal common format
try(
// 创建一些Socket连接 IO输出流...
){
// 可能会出现错误 通常是访问外部文件 链接网页
}catch(Exception ex){
// catch 根据 异常类型进行匹配来捕捉 相应类型的异常
// catch到了一个其实并没有checked Exception ,java程序会报错,因为java明确知道这个异常不会发生
}
/*
还有一种处理错误的方法 就是 向上抛出异常,在方法签名里添加 throws xx异常
*/
The usual treatment is usually exception Exception
For in Error exception in the code we can not handle, such as lack of a common memory, disk space access failure and so on.
throwable exception of all parent
comprising Exception and Error
and RuntimeException are checked Exception and Error parent
Treated in different ways is divided into two kinds checked and unchecked
checked Exception is an exception must use more than 2 ways to deal with
and can not be unchecked Exception exception handling
, but will throw runtime exceptions
such as
String str = null;
null.toLowercase();
// 此时抛出了 nullpointerException
Custom exception
java package to our common exception classes, if necessary on a business, you can create your own exception classes, the type of error message and call stack when an error is thrown.
public class MyRuntimeException extends RuntimeException{
//可以用 IDE 自动生成
public MyRuntimeException (){}
public MyRuntimeException (String message){
super(message);
}
public MyRuntimeException (String message, Throwable cause){
super(massage,cause);
}
public MyRuntimeException (Throwable cause){
super(cause);
}
}
// 封装好 上面的类
public void callThrowRTException(){
try{
// 下列会抛出 nullpointerException
Object n = null;
n.toString();
}catch(Exception ex){
// 捕捉到 异常之后 抛出 自定义的异常类
throw new MyRuntimeException(" 执行callThrowRTException 出错",ex);
}
}
Complete the form Try - catch - finally
3 forms
try {
}catch{
}finally{
finally 里 最好不要写 return 语句。
若写了有return 则会把 try,catch的语句覆盖掉,相当于无视try ,catch中的return。
}
try{
}catch(**ClassNotFoundException** e){
}catch(**IOException** e){
}
// 简化 版本:
try{
}catch(ClassNotFoundException | IOException e){
}
type of catch can not have multiple possible, or will be error
such as catch the Exception can not catch ClassNotFoundException
have A return value of the variable in the try, catch in, finally in the A variable assignment, then the assignment is invalid.
Notes
can not abnormal as Lingboweibu, serve as a means to jump between the methods.
Because to capture very abnormal consumption of resources.