The difference between runtimeexception and exception in Java

Source: Internet
Author: User
Tags integer numbers stub

In Java's exception class system, error and runtimeexception are non-check exceptions, others are check-type exceptions.


All methods can throw runtimeexception and its subclasses without declaring throws

Non-runtimeexception can not be thrown without declaration

Simply put, the non-runtimeexception to write the catch block itself.

1.RuntimeException

Today, Morgan it electric plane was asked about the difference between exception and runtimeexception, at that time can not answer, big embarrassed, come to study in the evening.

First look at a piece of code, the main content is to convert the string type of numbers into integer numbers, and then multiply two numbers, the code is as follows:

View Code
public class RuntimeException {public    static void Main (string[] args) {        //TODO auto-generated method stub        St Ring str= "123";        int Temp=integer.parseint (str);        System.out.println (temp*temp);    }}

The source code for the parseint method is as follows:

View Code
   public static int parseint (String s) throws NumberFormatException {    return parseint (s,10);    }

We found that the NumberFormatException exception was thrown in this method, but in the above code we did not find try...catch to handle it. According to our knowledge of exception handling, if a method throws an exception through throws, you can not apply Try...catch in the method that throws the exception, but there must be a try...catch to handle it where the method is called.

The following is an observation of the inheritance relationship of the NumberFormatException class:

From what we can find NumberFormatException is a subclass of RuntimeException, then this requires us to understand the concepts of exception and RuntimeException:

    1. Exception: You must use Try...catch for processing in your program.
    2. RuntimeException: It can be handled without using try...catch, but if there is an exception, the exception is handled by the JVM.

For RuntimeException subclasses it is best to also use exception handling mechanisms. Although runtimeexception exceptions can be handled without the use of Try...catch, if an exception occurs, it is sure to cause the program to break execution, so in order to ensure that the program can still execute after the error, it is best to use try when developing the code ... The exception handling mechanism for catch is processed.

2.User Defined Exception

The following is an example of a custom exception:

View Code
Class MyException extends exception{public    myexception (String msg) {        super (msg);}    }  public class Defaultexception {    /**     * @param args */public    static void Main (string[] args) {        //TODO auto-generated method Stub        try{            throw new MyException ("Custom Exception");        catch (Exception e) {            System.out.println (e);//edu.sjtu.ist.comutil.myexception: Custom Exception            // System.err.println (e);//            e.printstacktrace ();//            stacktraceelement[] sts = E.getstacktrace ();//For            (Stacktraceelement st:sts) {//                System.err.println (ST);/        /}//    System.err.println (E.getstacktrace ())        ;    }}}

The output is:

MyException: Custom exception

Common runtimeexception--

RuntimeException is the easiest to encounter in development, the following is a list of common runtimeexception:

1, NullPointerException : See the most, in fact, is very simple, it is generally called on a null object on the method.
      string S=null;
      boolean eq=s.equals (""); NullPointerException
    Here you see very clearly, why in the process of the faint?  
   public int getnumber (String str) {
if (str.equals ("A")) return 1;
else if (str.equals ("B")) return 2;
   }
    This method is likely to throw nullpointerexception, I suggest you actively throw an exception, because the code is more, you may faint again.
   public int getnumber (String str) {
if (str==null) throw new NullPointerException ("parameter cannot be null");
                                    //  Do you feel much more clear
if (str.equals ("A")) return 1;
    else if (str.equals ("B")) return 2;
   }

2,numberformatexception: Inherit IllegalArgumentException, the string is converted to a number appears. such as int i= integer.parseint ("ab3");

3,arrayindexoutofboundsexception: Array out of bounds. such as int[] a=new int[3]; int b=a[3];

4,stringindexoutofboundsexception: string out of bounds. such as String s= "Hello"; Char C=s.chatat (6);

5,classcastexception: type conversion error. such as Object Obj=new object (); String s= (string) obj;

6,unsupportedoperationexception: This operation is not supported. If we want to not support this method, we can throw this exception. Why do you want this if you don't support it? It is possible that the subclass does not want to support any of the methods in the parent class and can throw the exception directly.

7,arithmeticexception: Arithmetic error, typical is 0 as the divisor of time.

8,illegalargumentexception: illegal parameters, when converting a string into a number of a common exception, we can make good use of this exception in their own programs.

The difference between runtimeexception and exception in Java

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.