Home PC Games Linux Windows Database Network Programming Server Mobile  
  Home \ Programming \ Analysis of Java exception     - Linux find and xargs (Linux)

- MongoDB fragmentation (Cluster) (Database)

- Java polymorphism and exception handling (Programming)

- Installing software on Ubuntu: apt-get and dpkg difference (Linux)

- Linux cd command Detailed (Linux)

- JVM garbage collector and memory allocation strategy (Programming)

- RPM package management tools under Linux (Linux)

- command-line tool for send e-mail (Linux)

- HttpClient4 usage upgrade from HttpClient3 (Programming)

- Oracle JDK installation under Ubuntu Linux (Linux)

- Oracle 11g + RAC + RHEL6.5 + udev + ASM + PSU installation summary (Database)

- Not safe procedure under Linux (Linux)

- Git uses a basic tutorial (Linux)

- BusyBox build root file system (Linux)

- SQLite3 simple operation (Database)

- Android timer use (Programming)

- Install Git on CentOS (Linux)

- Source code to compile and install MySQL 5.7.9 (Database)

- Let Linux boot methods to enter characters interface and set FrameBuffer resolution methods (Linux)

- How to choose the first programming language based on the life you want (Programming)

  Analysis of Java exception
  Add Date : 2018-11-21      
  1. What is unusual

Poorly structured code can not run, which is the basic concept of Java.

Ideal time to discover the error is at compile time. However, the compiler can not find all the bugs, we need to resolve the remaining issues in the program is running. This requires some way of error, to pass appropriate information to a particular receiver processing. Purpose Java Exception handling is by using a small amount of code to simplify the generation of large, reliable programs, and in this way to get your application in no unhandled errors, but it also brings a significant benefit: reduce error processing complexity of the code.

Exception, according to the literal meaning, the meaning of an accident. It was placed to understand the code level, which prevents the current method or scope to continue.

In Java, exceptions are treated as objects to handle, which is the base class Throwable.

2, the Java exception type

Java directly derived from Throwable Exception and Error. Exception is the basic type which can be thrown in the Java class libraries, methods and runtime failure may throw Exception abnormalities; Error represents compile-time and system errors. Exception class hierarchy

Typical RuntimeException include NullPointerException, IndexOutOfBoundsException, IllegalArgumentException, etc; non RuntimeException include IOException, ClassNotFoundException like.

And according to the way the compiler checks division, can be divided into abnormal checked exceptions (CheckedException) and unchecked exceptions (UncheckedException). Error and RuntimeException collectively referred UncheckedException, the reason why so called because the compiler does not check whether the method or process both types of exception thrown, resulting in this type of exception during compilation is not given, the default by the virtual machine provides treatment. In addition to these two types of Error and RuntimeException exception, other exceptions are called Checked exceptions.

3, Java how to handle exceptions

3.1 try-catch, try-finally, try-catch-finally

For checked exception type, we either deal with it or use throws throws in the method header.

public static void createFile () throws IOException {
    File file = new File ( "C: /test.txt");
    if (! file.exists ()) {
            file.createNewFile ();
public static void main (String [] args) {
    try {
        createFile ();
    } Catch (IOException ex) {
        // Handle exception here
About catch points to note:

1), abnormal type parameter must be Throwable class or subclass.

2), down from the catch phrase, it must follow the parameter types from the sub-class to the parent class order, because once matched to a type, it will ignore subsequent catch. For example IOException must be placed in front of Exception, otherwise the compiler will complain.

3), there may be one or more catch statements, even if there is finally under statement, the statement can not catch, such as try-finally.

Want to catch multiple exceptions, you can use multiple catch statements, provides another way JDK7 later: Multiple capture (multi-catch).

try {
    // Other code
} Catch (IOException | SQLException ex) {
    throw ex;
4) Do not ignore the exception. Empty catch block exception will achieve their purpose, unless such close FileInputStream time, because you do not have to change the status of the file, so you do not perform any recovery action, and has been read from the file to the desired information , so it does not terminate an ongoing operation.

About finally points to note:

1), finally the code is always executed, except when the try or catch statement VM exit (System.exit (1)).

2), finally block can do some cleanup work resources, such as closing a file, close the cursor operation.

3), finally block is not necessary.

In addition, if the try and finally block executes a return statement, the final returns will be finally the return value.

3.2 Exception chaining

Often they want to catch an exception after another exception is thrown, and you want to preserve the original exception information, which is the exception chain. In JDK1.4 later, Throwable subclass constructor can accept a cause object as a parameter representing the original exception, the original exception is passed through to this new exception, so that even if you create and throw a new exception in the current location, but also through the exception chain to track the location of abnormality occurred first.

But Throwable subclass, only Error, Exception, RuntimeException exception class provides three constructors with parameters cause other types of exceptions you need initCause () method. Such as the definition of the CustomException class, you can use:

CustomException cmex = new CustomException ();
cmex.initCause (new NullPointerException);
throw cmex;
As a result, CustomException inherited from Exception or RuntimeException, belongs to a custom exception.

Generally speaking, the role of custom exception of the following circumstances:

1), the checked exceptions into non-checked exceptions.

2) when an abnormal context information package, defined exception code, collect objects environment, conducive to the transmission of information.

4, abnormal Guide

1) In the case of know how to deal with only an exception.

2), custom exception type, in order to encapsulate all checked exceptions.

3), at the boundary of the program abnormal capture. The service ends of the respective client's request, at the exit of the catch may have internal abnormalities, and unified throw a package over the exception to the client, so that sensitive information is exposed server.

4), used only exception for extraordinary circumstances. Do not habitually use try-catch in all of the code, because this will affect the performance.

5), relatively abstract thrown exception. If the method throws an exception and the task it performs no obvious connection, this situation will make people confused. To avoid this problem, we should achieve a higher level of low-level exception catch, and throw out can be interpreted in accordance with the abnormal level of abstraction, a practice known as exception translation (exception translation), as follows:

try {
    // Use lower-level abstraction to do our bidding
} Catch (LowerLevelException ex) {
    throw new HigherLevelException (...);
Another special exception called translation exception chain, as has been described above. If the low-level exception for debugging problems cause abnormal rise very helpful, it is appropriate to use exception chaining. High-level exception provided access method (Throwable.getCause) to obtain a low-level exception.

6) each have an exception thrown document describes. Use the Javadoc @throws tag for each record throw exception conditions. If a method can throw multiple exceptions, do not use a superclass of these exception classes. Do not declare such a method "throws Exception" or "throws Throwable", which will not have any guidance.
- Linux Network Programming - raw socket programming (Programming)
- Ubuntu development Nodejs (Linux)
- 32-bit and 64-bit integer in PHP and MySQL range (Database)
- After restarting network services, DNS address failure (Linux)
- Linux file time Comments ctime mtime atime (Linux)
- The method of Linux into the rescue mode (Linux)
- Linux network security strategy (Linux)
- MySQL binary packages install for RedHat Linux Enterprise 6.4 (Database)
- Understanding Linux firewall Iptables (Linux)
- Debian installation (Linux)
- Arrow keys, backspace key garbled in Python-2.7.5 Interactive Mode under CentOS 5.8 (Linux)
- Linux System Getting Started Tutorial: Installing Git on Linux (Linux)
- Django1.5 Custom User Model (Programming)
- Java String type time compare the size (Programming)
- JavaScript cross-browser event object library (Programming)
- Oracle RMAN-06023 and ORA-19693 errors (Database)
- Using LLVM Clang and Blocks under Linux (Programming)
- OpenNMS compile under Linux (Server)
- QBit development of micro-services (Server)
- About Auto Layout and frame (Programming)
  CopyRight 2002-2020 newfreesoft.com, All Rights Reserved.