Try, catch, and finally encounter return

Source: Internet
Author: User

Java Exception Handling

The basic idea of Java is "" -- Thinking in Java.

Exception Handling in Java is an error reporting mechanism in the compilation phase, which is enforced by the compiler. But I still need to understand

Yes: no errors can be found during compilation, and the remaining problems must be solved during runtime.

Simply put, exception handling aims to make your program more reliable with a small amount of code.

Try, catch, and finally encounter return

I will not mention how to use exceptions in Java. I am interested in the try, catch, and finally blocks.

The execution of the return Statement and the return value (there are always written and interview questions ).

The first thing to note is that it is wrong to return the result and terminate the result when the return statement is executed by the method. The exception is the exception system of Java.

Let's look at the example program below:

package com.al;public class ExceptionTest{    @SuppressWarnings("finally")public String test(){    String returnStr ="start";    try {System.out.println("start String:"+returnStr);returnStr="try innner";throw new Exception("inner Exception");} catch (Exception e) {returnStr ="catch inner";return returnStr;}finally{returnStr = "finally";System.out.println("inner finally:"+returnStr);return returnStr;}    }        public static void main(String[] args) {ExceptionTest exceptionTest = new ExceptionTest();try {   String test=exceptionTest.test();Thread.sleep(300);System.out.println("returnString:"+test);} catch (InterruptedException e) {// TODO: handle exception}}}
Output result:

Start String: start
Inner finally: finally
ReturnString: finally

Understanding the following rules can solve the return problem.


Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.