异常的概念:
程序在执行过程中,出现意外,这种情况叫做出现了异常;
出现 异常之后,程序就终止了,不能继续运行下去;
那么,java程序中的异常我们可以捕获然后处理,这样后面的程序就可以继续执行了;
上代码:
package m12d28;
public class ExceptionDemo01 {
public static void main(String[] args) {
String s="123a";
try{
int a=Integer.parseInt(s);
}catch(Exception e){
e.printStackTrace();
System.out.println("异常执行");
}
System.out.println("继续执行");
}
}
输出结果:
如果在catch里面添加一个return的话;
package m12d28;
public class ExceptionDemo01 {
public static void main(String[] args) {
String s="123a";
try{
int a=Integer.parseInt(s);
}catch(Exception e){
e.printStackTrace();
System.out.println("异常执行");
return;
}
System.out.println("继续执行");
}
}
结果是:
可以看到,加一个return的话就直接返回方法了,不会执行到后面的代码;
但是如果由一段代码必须执行的话,这时可以用到finally关键字;
package m12d28;
public class ExceptionDemo01 {
public static void main(String[] args) {
String s="123a";
try{
int a=Integer.parseInt(s);
}catch(Exception e){
e.printStackTrace();
System.out.println("异常执行");
return;
}finally{
System.out.println("finally");
}
System.out.println("继续执行");
}
}
运行结果:
可以看到finally也执行了;
throws 和 throw;
throws表示当前方法不处理异常,而是交给方法的调用出去处理;
throw表示直接抛出一个异常;
throws的用法:
package m12d28;
public class throwsException {
public static void throwException() throws NumberFormatException{
String s="123a";
int a=Integer.parseInt(s);
System.out.println(a);
}
public static void main(String[] args) {
try{
throwException();
System.out.println("here");
}catch(Exception e){
e.printStackTrace();
System.out.println("在这里处理异常");
}
System.out.println("在这里");
}
}
这里是直接将异常抛给方法的调用;
结果为:
throw的用法:
package m12d28;
public class throwsException2 {
public static void throwException(int a) throws Exception{
if(a==1){
throw new Exception("有异常");
}
}
public static void main(String[] args) {
try{
throwException(1);
}catch(Exception e){
e.printStackTrace();
}
}
}
这里可以在任何一个地方抛出异常;
结果为:
在实际开发中,throws关键字用得较多;