1. runtimeexception
I was asked about the difference between exception and runtimeexception when I was asked about Morgan it today. I couldn't answer the question at that time. I 'd like to know about it later.
First, take a lookCodeThe main content is to convert a string-type number into an integer number and then multiply the two numbers. The Code is as follows:
View code
Public ClassRuntimeexception {Public Static VoidMain (string [] ARGs ){//Todo auto-generated method stubString STR = "123";IntTemp =Integer. parseint (STR); system. Out. println (temp*Temp );}}
ViewSource codeAs follows:
View code
Public Static IntParseint (string S)ThrowsNumberformatexception {ReturnParseint (s, 10);}
We found that the numberformatexception was thrown in this method, but we didn't find try... catch in the above Code to handle it. Why.According to our knowledge about exception handling, if an exception is thrown through throws, try... catch, but there must be try... catch.
Next we will observe the inheritance relationship of the numberformatexception class:
We can find that numberformatexception is a subclass of runtimeexception, so we need to understand the concepts of exception and runtimeexception:
- Exception: InProgramTry... catch must be used for processing.
- Runtimeexception: Try... catch is not used for processing. However, if an exception is generated, the exception will be handled by JVM.
The exception handling mechanism is also recommended for subclasses of runtimeexception. Although the exception of runtimeexception does not support try... if an exception occurs, the program will be interrupted. Therefore, to ensure that the program can still be executed after an error occurs, try... catch exception handling mechanism.
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 ()); }}}
Output result:
Myexception: custom exception