第一节 异常的概念
第二节 捕获和处理异常
在java中,使用try...catch...来捕获异常
try...catch...finally
public class Demo {
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
String a="123a";
try{
int i=Integer.parseInt(a);
}catch(NumberFormatException e){
e.printStackTrace();
}
System.out.println(a);
}
}
》》》》》》》》》》
public class Demo1 {
public static void testFinally(){
String s="123a";
try{
int i=Integer.parseInt(s);
}catch(Exception e){
e.printStackTrace();
System.out.println("exception");
return;
}finally{
System.out.println("final end");
}
System.out.println("end");
}
public static void main(String args[]){
testFinally();
}
}
第三节 Throws和throw关键字
throws 表示当前方法不处理异常,而是交给方法的调用处去处理
Throw 表示直接抛出一个异常
public class Demo2 {
public static void testThrows ()throws NumberFormatException{
String s="123a";
int i=Integer.parseInt(s);
System.out.println(i);
}
public static void main(String args[]){
try{
testThrows();
System.out.println("here");
}catch(Exception e){
System.out.println("这里处理异常");
e.printStackTrace();
}
System.out.println("I'm here");
}
}
》》》》》》》》》》》》》
public class Demo3 {
public static void TestThrow(int a)throws Exception{
if(a==1){
throw new Exception("这里异常");
}
System.out.println(a);
}
public static void main(String args[]){
try {
TestThrow(1);
} catch (Exception ex) {
Logger.getLogger(Demo3.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
第四节 Exception和RuntimeException区别
Exception是检查型异常,在程序中必须使用try...catch...进行处理
RuntimeException 是非检查型异常,例如NumberFormatException,可以不使用try...catch...进行处理,但是如果产生异常,则异常将由JVM进行处理;
RuntimeException最好也用try...catch...进行处理
public class Demo4 {
//运行时异常,编译时不检查,可以不使用try...catch...捕获
public static void TestRuntimeException()throws RuntimeException{
throw new RuntimeException("运行时异常");
}
//编译时异常,必须需用try...catch...捕获
public static void TestException()throws Exception{
throw new Exception("Exception异常");
}
public static void main(String args[]){
TestRuntimeException();//若不加try...catch 后面将不执行
try {
TestException();
} catch (Exception ex) {
Logger.getLogger(Demo4.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
第五节 自定义异常
public class CustomException extends Exception{
public CustomException(String message){
super(message);
}
}
》》》》》》》》》》》》
public class TestCustomException {
throw new CustomException("自定义异常");
}
public static void main(String args[]){
try {
TestCustomException();
} catch (CustomException ex) {
Logger.getLogger(TestCustomException.class.getName()).log(Level.SEVERE, null, ex);
}
}
}