Home > Java > javaTutorial > body text

Java Example - Usage of Finally

黄舟
Release: 2017-02-04 10:16:12
Original
1388 people have browsed it

The Finally key in Java is generally used together with try. After the program enters the try block, whether the program is terminated due to an exception or otherwise, the contents of the finally block will definitely be executed.

The following example demonstrates how to use finally to catch exceptions (illegal parameter exceptions) through e.getMessage():

/*
 author by w3cschool.cc
 ExceptionDemo2.java
 */

public class ExceptionDemo2 {
   public static void main(String[] argv) {
      new ExceptionDemo2().doTheWork();
   }
   public void doTheWork() {
      Object o = null;
      for (int i=0; i<5; i++) {
         try {
            o = makeObj(i);
         }
         catch (IllegalArgumentException e) {
            System.err.println
            ("Error: ("+ e.getMessage()+").");
            return;   
         }
         finally {
            System.err.println("都已执行完毕");
            if (o==null)
            System.exit(0);
        }
        System.out.println(o); 
      }
   }
   public Object makeObj(int type) 
   throws IllegalArgumentException {
      if (type == 1)  
      throw new IllegalArgumentException
      ("不是指定的类型: " + type);
      return new Object();
   }
}
Copy after login

The output result of running the above code is:

都已执行完毕
java.lang.Object@7852e922
Error: (不是指定的类型:1).
都已执行完毕
Copy after login

Above It is the content of Java Example-Finally usage. For more related content, please pay attention to the PHP Chinese website (www.php.cn)!


Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!