Exception handling _java Java Advanced Tutorials

Source: Internet
Author: User
Tags exception handling finally block getmessage readline throwable java throws

It's hard to be perfect, and there are all kinds of anomalies. For example, the program itself has bugs, such as when the program prints the printer does not have paper, such as insufficient memory. In order to solve these anomalies, we need to know the cause of the abnormal occurrence. For some common anomalies, we can also provide a certain response plan. The exception handling in C language is simply achieved by the function return value, but the meaning of the return value is often determined by practice. Programmers need to query a lot of information before they can find a vague reason. Object-oriented languages, such as C + +, Java, and Python, often have more complex exception handling mechanisms. This discusses the exception handling mechanism in Java.

Java Exception Handling

Exception handling

A large part of the Java exception handling mechanism comes from C + +. It allows programmers to skip issues that are temporarily out of the way to continue development, or to make the program smarter to handle exceptions.

Java uses special objects to represent exceptional conditions, such that objects are called exception objects. When an exception occurs, Java throws (throw) The object that represents the current condition, depending on the preset settings. The so-called throw is a special way of return. The thread pauses, stepping out of the method call until the exception handler (Exception Handler) is encountered. The exception handler can catch (catch) The exception object and determine the next action based on the object, such as:

Remind users
Handling Exceptions
Continue Program
Exit program
......

The exception handler looks like this, consisting of try, catch, finally, and subsequent blocks of the program. Finally, it is not necessary.

try {

 ...;

}

catch () {

 ...;

}

catch () {

 ...;

}

finally {

 ...;

}

This exception handler monitors the program block behind the try. A catch has a parameter that represents the type of exception that you want to catch. Catch captures the corresponding type and its derived classes. The program block after the try contains the action to be taken against the exception type. The block that the try is monitoring may throw more than one type of exception, so an exception handler can have more than one catch module. Finally, the program block is the program to execute regardless of whether an exception occurred.

We put in a try a program that may be wrong, need to be monitored, and design a solution to the exception in a catch.

The following is a section of Java programs that use exception handling. A program in the try section reads lines of text from a file. In the process of reading a file, IOException may occur:

BufferedReader br = new BufferedReader (New FileReader ("file.txt"));
try {
  StringBuilder sb = new StringBuilder ();
  String line = Br.readline ();

  While [line!= null] {
    sb.append (line);
    Sb.append ("\ n");
    line = Br.readline ();
  }
  String everything = sb.tostring ();
} 
catch (IOException e) {
  e.printstacktrace ();
  System.out.println ("IO problem");
}
finally {
  br.close ();
}

If we capture the IOException class object E, you can manipulate the object. For example, call the object's Printstacktrace (), print the status of the current stack. In addition, we also printed the tip "IO problem" to the midrange.

Regardless of whether there is an exception, the program eventually enters the finally block. We close the file in the finally block and empty the resource occupied by the file descriptor.

Type of exception

Exception classes in Java inherit from the Trowable class. An object of a Throwable class can be thrown (throw).

Orange: unchecked; Blue: Checked

Throwable objects can be grouped into two groups. One group is a unchecked exception, and the exception handling mechanism is often not used for this set of exceptions, including:

The 1.Error class typically refers to Java internal errors and errors such as resource depletion. When the error (and its derived class) occurs, we cannot solve the error at the programming level, so we should exit the program directly.

The 2.Exception class has a special derivative class runtimeexception. RuntimeException (and its derived classes) is caused by the Java program itself, that is, because programmers make mistakes in programming. RuntimeException can be avoided by modifying Java programs entirely. For example, convert an object of one type to another type that has no inheritance relationship, that is, classcastexception. Such exceptions should and can be avoided.

The rest is checked anomaly. These classes are programmed to interact with the environment, causing the program to make errors at run time. For example, when reading a file, because the file itself error, occurs IOException. For example, the Web server temporarily changes the URL point, causing malformedurlexception. File systems and Web servers are outside of the Java environment and are not controlled by programmers. If the programmer can anticipate the exception, the exception handling mechanism can be used to formulate the response plan. For example, when a file problem, remind the system administrator. For example, when a problem occurs on a network server, alert the user and wait for the network server to recover. The exception handling mechanism is primarily used to handle such exceptions.

Throw an exception

In the above program, the exception comes from our invocation of the Java IO API. We can also throw exceptions in our own programs, such as the following battery class, charging and using methods:

public class Test {public static void main (string[] args) {Battery abattery = new Battery ();
    Abattery.chargebattery (0.5);
  Abattery.usebattery (-0.5);
    } class Battery {/** * increase Battery/public void Chargebattery (double p) {//Power <= 1 if (This.power + P < 1.)
    {this.power = This.power + p;
    else {this.power = 1.;
    }/** * Consume battery/public boolean usebattery (double p) {try {Test (P);
      catch (Exception e) {System.out.println ("catch Exception");
      System.out.println (E.getmessage ());
    p = 0.0;
      } if (This.power >= p) {this.power = this.power-p;
    return true;
      else {this.power = 0.0;
    return false;  }/** * Test usage/private void Test (double p) throws Exception//I just throw, don ' t handle {if (P < 0)
      {Exception e = new Exception ("P must be positive"); Throw e; } private double power = 0.0; Percentage of battery}

Usebattery () indicates the use of battery operation. The Usebattery () method has a parameter that represents the amount of electricity used. We test the parameter using the test () method. If the argument is negative, then we think there is an exception and throw it.

In test, when an exception occurs (P < 0), we create a exception object E and use a string as a parameter. The string contains an exception-related information that is not required. Use throw to throw the exception object.

We have an exception handler in the Usebattery (). Because the test () method does not directly handle the exception it produces, it throws the exception to the Upper Usebattery (), so in the definition of test (), we need throws exception to explain it.

(Assuming that the exception handler is not located in Usebattery (), but rather in the higher layer Main () method, we also add throws Exception to the definition of usebattery (). )

In catch, we use the GetMessage () method to extract the information contained in its exception. The results of the above procedures are as follows:

Catch Exception
P must be positive

In the exception handler, we will catch any exception class or its derived class exception. This often does not help us identify problems, especially when a program may throw a variety of exceptions. We can provide a more specific class to capture.

Custom exceptions

We can create a new exception class by inheriting it. When inheriting, we often need to rewrite the constructor method. An exception has two constructor methods, one with no arguments, and one with a string argument. Like what:

Class Batteryusageexception extends Exception
{public
  batteryusageexception () {}
  Batteryusageexception (String msg) {
    super (msg);
  }
}

We can provide more exception-related methods and information in the derived class.

When customizing an exception, be careful to select the inherited base class. A more specific class should contain more exception information, such as IOException relative to exception.

Summarize

Exception handling is both a problem and a manufacturing problem. In large projects, excessive and meticulous exception handling often causes the program to become a mess. The design of exception handling is not simple and requires careful use.

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.