- public class FinallyTest {
- public static void main(String[] args) {
- int res=div(10,0);
- System.out.println(res);
- }
- public static int div(int a,int b){
- int num=0;
- try {
- num=a/b;
- }catch (ArithmeticException e){
- System.out.println("算数异常");
- }catch (NumberFormatException e){
- e.printStackTrace();
- }catch (Exception e){
- System.out.println("其他异常");
- }finally {
- System.out.println("一定执行的语句");
- }
- return num;
- }
- }
-
- public class FinallyTest {
- public static void main(String[] args) {
- int res=div(10,0);
- System.out.println(res);
- }
- public static int div(int a,int b){
- int num=0;
- try {
- num=a/b;
- }catch (ArithmeticException e){
- System.out.println("算数异常");
- return 11;
- }catch (NumberFormatException e){
- e.printStackTrace();
- }catch (Exception e){
- System.out.println("其他异常");
- }finally {
- System.out.println("一定执行的语句");
- }
- return num;
- }
- }
-
结论:
finally 是可选的,一旦写上就一定执行的语句,即使过程中有return也一定执行
- /*
- finally 是可选的,一旦写上就一定执行的语句,即使过程中有return也一定执行
- */
- public class FinallyTest {
- public static void main(String[] args) {
- int res=div(10,0);
- System.out.println(res);
- }
- public static int div(int a,int b){
- int num=0;
- try {
- num=a/b;
- }catch (ArithmeticException e){
- System.out.println("算数异常");
- return 11;
- }catch (NumberFormatException e){
- e.printStackTrace();
- }catch (Exception e){
- System.out.println("其他异常");
- }finally {
- System.out.println("一定执行的语句");
- return 22;
- }
- }
- }
-
- /*
- finally 是可选的,一旦写上就一定执行的语句,即使过程中有return也一定执行
- */
- public class FinallyTest {
- public static void main(String[] args) {
- int res=div(10,0);
- System.out.println(res);
- }
- public static int div(int a,int b){
- int num=0;
- try {
- num=a/b;
- }catch (ArithmeticException e){
- System.out.println("算数异常");
- return num;
- }catch (NumberFormatException e){
- e.printStackTrace();
- }catch (Exception e){
- System.out.println("其他异常");
- }finally {
- num+=100;
- System.out.println("一定执行的语句");
- }
- return num;
- }
- }
-
- /*
- finally 是可选的,一旦写上就一定执行的语句,即使过程中有return也一定执行
- */
- public class FinallyTest {
- public static void main(String[] args) {
- int res=div(10,0);
- System.out.println(res);
- }
- public static int div(int a,int b){
- int num=0;
- try {
- num=a/b;
- }catch (ArithmeticException e){
- System.out.println("算数异常");
- return num;
- }catch (NumberFormatException e){
- e.printStackTrace();
- }catch (Exception e){
- System.out.println("其他异常");
- }finally {
- num+=100;
- System.out.println("一定执行的语句");
- return num;
- }
- }
- }
-