"Simple Java" 10 frequently asked questions about Java exceptions

Source: Internet
Author: User

This article summarizes 10 frequently asked Java exception problems;

1. Check type exception vs non-check type exception

To put it simply, the check-type exception refers to the need to catch exception handling in the method itself or declare the exception to be thrown by the caller to capture the processing;

Non-check exceptions refer to exceptions that cannot be resolved, such as 0, null pointers, etc.;

Checking for exceptions is important because you want people using your API interface to know how to handle these exceptions;

For example, IOException is a very common check-type anomaly, RuntimeException is a non-check type anomaly;

The exception hierarchy diagram for Java is as follows:

2. Exception Management Best Practices

If an exception is currently handled appropriately, it should be caught to handle it, otherwise the thrown exception should be displayed;

3. Why variables defined in a try code block cannot be accessed in a catch or finally code block

The following code declares the string s variable in a try code block, but cannot be used in a catch block, and the code cannot be compiled;

        Try {            new File ("path");             New fileinputstream (file);             = "Inside";         Catch (FileNotFoundException e) {            e.printstacktrace ();            System.out.println (s);        }

The reason is because you do not know which sentence in the try code block throws an exception, it is possible that the exception was thrown before the variable declaration;

This is precisely the case of the above example;

Note: Strongly suspect that the s variable is not visible because of the scope relationship;

4. Why Integer.parseint (NULL) and double.parsedouble (null) throw different exceptions

This is the JDK problem, because these two methods are written by different developers, so there is no need to delve into it;

        Integer.parseint (null);         // throws Java.lang.NumberFormatException:null        Double.parsedouble (null);         // throws Java.lang.NullPointerException

Note: In fact, my current JDK7 has no problem, two are thrown numberformatexception

5. Multi-use run-time exceptions

Several common run-time exceptions, such as IllegalArgumentException, arrayindexoutofboundsexception;

These exceptions can be thrown when the judging condition is not satisfied, as in the following code:

        if NULL {            thrownew illegalargumentexception ("obj can not is null");
6. Whether multiple exceptions can be caught in a catch code block

The answer is yes. Because Java exceptions can be traced back to the same parent class exception, we can use the parent class to capture multiple exceptions;

        Try {                    catch  (Exception e) {            //  todo:handle Exception        }

Add:

In JAVA7, a new syntax is added that can capture multiple exceptions in this way:

Try {   catch(IOException |  SQLException ex) {   ...}

This can be written before JAVA7:

Try {  //.....}Catch(Exception exc) {if(excinstanceofIllegalArgumentException | | ExcinstanceofSecurityException | |excinstanceofillegalaccessexception | | Excinstanceofnosuchfieldexception)  {Somecode (); } Else if(excinstanceofruntimeexception) {     Throw(runtimeexception) exc; } Else {    Throw Newruntimeexception (EXC); }}
7. Whether the construction method can throw an exception

The answer is yes, the construction method is a special method, the same can throw an exception;

Note that if the construction method throws an exception, the object is not generated;

8.finally statement blocks can also throw and catch exceptions

The following code is legal:

     Public Static voidMain (string[] args) {File file1=NewFile ("path1"); File file2=NewFile ("path2"); Try{FileInputStream fis=NewFileInputStream (FILE1); } Catch(FileNotFoundException e) {e.printstacktrace (); } finally {            Try{FileInputStream fis=NewFileInputStream (file2); } Catch(FileNotFoundException e) {e.printstacktrace (); }        }    }

However, for readability, it is best to encapsulate the exception handling code in finally in a method, and then call the method, which is the following code:

     Public Static void Main (string[] args) {        new File ("path1");         New File ("path2");         Try {            new  FileInputStream (file1);         Catch (FileNotFoundException e) {            e.printstacktrace ();         finally {            methodthrowexception ();        }    }
Whether a return statement can be written in a 9.finally code block

Yes, I can.

10. Why Java programmers often silently ignore the handling of exceptions

The following code snippet often appears in the program, and if exception handling is so important, why are so many developers doing it all the time?

        Try  {            ...         Catch (Exception e) {            e.printstacktrace ();        }

The code that often appears does not mean that it is right;

Many developers may use Eclipse's quick fix to automatically generate exception handling code, as shown above, in fact, in addition to logging the log, there is no processing;

As described in entry 2, if the exception is not handled correctly, it is best to throw an exception so that the exception is detected early;

Link: http://www.programcreek.com/2013/10/top-10-questions-about-java-exceptions/

"Simple Java" 10 frequently asked questions about Java exceptions

Related Article

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.