Java Foundation Chapter III (Exception mechanism in java,c++)

Source: Internet
Author: User
Tags throw exception throwable

Because C + + and Java have a lot of similarities, and there are a lot of subtle differences, so in the process of learning Java in the two languages to compare learning.

1. Exception mechanism of C + +

The process of handling exceptions in C + + is this: in the execution of the program exception, can not be processed in this function, but instead of throwing an error message, pass it to the previous level of the function to resolve, the upper level can not be resolved, and then passed to its upper level, by its upper level processing. By uploading it so that the top level is not able to handle it, the operating system automatically calls the system function terminate, which calls abort to terminate the program. Such an exception-handling method separates exception-throwing from the processing mechanism, rather than processing it in the same function. This makes the underlying function only needs to solve the actual task, without too much consideration of the exception handling, and the exception handling task to the previous layer of function to deal with.

C + + 's exception handling mechanism consists of 3 parts: try (check), throw (throw), catch (catch). Put the required check in the Try module, check the statement error, throw throws an exception, send an error message, catch to catch the exception information, and to be processed. The exception thrown by the general throw is matched to the type of exception caught by the catch. The general format for exception handling is:

Try

{

Checked statements

Throw exception

}

catch (Exception type 1)

{

Statement for exception handling 1

}

catch (Exception type 2)

{

Statement for exception Handling 2

}

#include <iostream>  #include <cstdlib>  using NAMESPCE std;    Class myexception{};    void f (int) throw (myexception);       Throw (myexception) is optional, (compared to Java), if throw (), no exception is thrown    int main ()  {    try{         f (0);    }    catch (MyException &e) {             //parameter list can have only type, excluding object (more than Java)        cout<< "catch to Exception";    }    return 0;  }    void f (Int j) throw (MyException)  {    throw myexception ();  }  

2. Java Exception mechanism

Java treats exceptions as objects and defines a base class java.lang.Throwable as a superclass of all exceptions. Many exception classes have been defined in the Java API, and these exception classes fall into two main categories, error errors and exception exception.

The exception class Exception is divided into run-time exceptions (RuntimeException) and non-runtime exceptions, the two exceptions are very different, also known as the non-check exception (unchecked Exception) and check the exception (Checked Exception). The differences and linkages between these exceptions are described in detail below:

(1), error and exception errors is the program can not handle the mistakes, such as OutOfMemoryError, Threaddeath and so on.     When these exceptions occur, the Java Virtual machine (JVM) typically chooses to terminate the thread. Exception is an exception that the program itself can handle, which is divided into two classes of runtime exceptions and non-runtime exceptions. These exceptions should be handled as much as possible in the program.

(2), run-time exceptions and non-runtime exceptions

Run-time exceptions are runtimeexception classes and their subclass exceptions, such as NullPointerException, Indexoutofboundsexception, and so on, which are not checked for exceptions, can be selected for capture processing in the program, or can not be processed. These exceptions are usually caused by a program logic error, and the program should avoid this kind of exception as much as possible from a logical point of view.

A non-runtime exception is an exception that is runtimeexception except that the type belongs to the exception class and its subclasses. From the point of view of the program syntax is the exception that must be handled, and if not handled, the program cannot be compiled through. such as IOException, SqlException, and user-defined exception exceptions, generally do not customize check exceptions.

Java exception handling involves five keywords, namely: try, catch, finally, throw, throws.

In Java, the complete syntax for exception handling is:

try{

Program code (trying to run)

}catch (variable name for exception type exception) {

Exception handling code

}

finally{

The code that is always executed before the exception occurs, before the method returns

}

The Throw keyword is used inside the method body to throw an exception of type Throwable. If you throw a check exception, you should also declare the type of exception that the method might throw on the method header. The caller of the method must also check the exception that is thrown by the handle. If all of the methods are thrown at layers, the JVM will eventually be processed and the processing is simple, which is to print the exception message and stack information. If an error or runtimeexception is thrown, the caller of the method can choose to handle the exception.    The translation of the exception is described below. The throws keyword is used in the method declaration section outside the method body to declare that the method may throw some exceptions. Only if a check exception is thrown, the caller of the method must handle or re-throw the exception. When the caller of the method is unable to handle the exception, it should continue to throw, rather than swallowed generally print the stack information in the catch block and do a little bit of processing.

Simple list (copy others, lazy to write):

Package Code;class MyException extends exception{public void f () {System.out.println ("This is my exception! !");     }}      public class Exceptiontesttwo {private int i = 0;       private int J;          Exceptiontesttwo (int x) throws MyException {F2 ();        j = x/i;          } public void F2 () throws MyException {System.out.println ("This is My first exception!!");       throw new MyException ();              } public static void Main (string[] args) {try {new exceptiontesttwo (9);               } catch (MyException E2) {e2.f ();               } catch (Exception e) {e.printstacktrace ();                } finally {System.out.println ("Finally is first exception!!");           } try {throw new myexception ();            } catch (MyException E1) {e1.f (); } finally {System.out.println ("finallyis second exception!! ");}} 


Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.

Java Foundation Chapter III (Exception mechanism in java,c++)

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.