Java exception handling and use of custom exceptions

Source: Internet
Author: User
Tags instance method throwable

1. Introduction to Exceptions

The abnormal mechanism can improve the robustness and fault tolerance of the program.

Throwable:throwable is a superclass of all errors or exceptions in the Java language. There are two sub-classes of error and exception.

1.1 Compile-time exception

  The compile-time exception must be handled or the compilation cannot pass.

Aclnotfoundexception, Activationexception, Alreadyboundexception, ApplicationException, AWTException, Backingstoreexception, Badattributevalueexpexception, Badbinaryopvalueexpexception, BadLocationException, Badstringoperationexception, Brokenbarrierexception, Certificateexception, ClassNotFoundException, Clonenotsupportedexception, Dataformatexception, Datatypeconfigurationexception, DestroyFailedException, Executionexception, Expandvetoexception, Fontformatexception, Generalsecurityexception, GSSException, Illegalaccessexception, Illegalclassformatexception, Instantiationexception, Interruptedexception, Introspectionexception, Invalidapplicationexception, Invalidmididataexception, Invalidpreferencesformatexception, Invalidtargetobjecttypeexception, InvocationTargetException, IOException, Jaxbexception, JMException, Keyselectorexception, Lastownerexception, Lineunavailableexception, Marshalexception, MidiUnavailableException, Mimetypeparseexception, Mimetypeparseexception, NAMINGEXCEPtion, noninvertibletransformexception, nosuchfieldexception, Nosuchmethodexception, NotBoundException, Notownerexception, ParseException, Parserconfigurationexception, PrinterException, PrintException, Privilegedactionexception, Propertyvetoexception, Refreshfailedexception, Remarshalexception, SAXException, Scriptexception, Servernotactiveexception, SoapException, SQLException, TimeoutException, toomanylistenersexception , Transformerexception, Transformexception, Unmodifiableclassexception, Unsupportedaudiofileexception, Unsupportedcallbackexception, Unsupportedflavorexception, Unsupportedlookandfeelexception, URIReferenceException, URISyntaxException, Userexception, Xaexception, Xmlparseexception, Xmlsignatureexception, XMLStreamException, XPathException

 

1.2 Run-time exception ( RuntimeException)

Annotationtypemismatchexception, ArithmeticException, Arraystoreexception, Bufferoverflowexception, Bufferunderflowexception, Cannotredoexception, Cannotundoexception, ClassCastException, CMMException, Concurrentmodificationexception, Domexception, Emptystackexception, Enumconstantnotpresentexception, Eventexception, IllegalArgumentException, Illegalmonitorstateexception, Illegalpathstateexception, IllegalStateException, Imagingopexception, Incompleteannotationexception, Indexoutofboundsexception, Jmruntimeexception, Lsexception, Malformedparameterizedtypeexception, Mirroredtypeexception, Mirroredtypesexception, MissingResourceException, Negativearraysizeexception, Nosuchelementexception, Nosuchmechanismexception, NullPointerException, Profiledataexception, ProviderException, RasterFormatException, Rejectedexecutionexception, SecurityException, SystemException, Typeconstraintexception, TypeNotPresentException, Undeclaredthrowableexception, Unknownannotationvalueexception, UnknownelemenTexception, Unknowntypeexception, Unmodifiablesetexception, Unsupportedoperationexception, WebServiceException 

NullPointerException and Indexoutofboundsexception are common run-time anomalies.

Example:

    Public Static void Main (string[] args) {        intnewint[ten];         NULL ;        System.out.println (Array.Length);    }
Exception in thread "main" Java.lang.NullPointerExceptionat Lang. Object.ExceptionTest.main (EXCEPTIONTEST.JAVA:18)

About the NPE exception

This exception is thrown when an application tries to use the object where it is needed null . This situation includes:

    • Invokes null an instance method of an object.
    • Access or modify null The fields of an object.
    • will be null used as an array to get its length.
    • will be null used as an array to access or modify its time slice.
    • Will null be Throwable thrown as a value.

An application should throw an instance of the class, indicating other null illegal use of the object.

2. Handling of abnormal operation period

Exceptions can be captured using catch and then processed.

    @Test    publicvoid  testarithmeticexception () {        try  {             int result = 10/0;            System.out.println ("code after exception in try will not execute");         Catch (ArithmeticException e) {            System.out.println ("Exception handling:");            System.out.println (E.getmessage ());        }        System.out.println ("code after Try...catch can be executed");    }

3. Throw of the run-time exception

  Without processing, the exception can be thrown to the upper layer for processing by the upper layer.

     Public Static voidMain (string[] args) {Try{testnullpointerexception (); } Catch(NullPointerException e) {e.printstacktrace (); System.out.println ("Exceptions are handled by the upper layer"); }        //If an exception occurs in the preceding code, the following code will not executeSystem.out.println ("Call succeeded"); }     Public Static voidtestnullpointerexception () {int[] Array =New int[10]; Array=NULL; //because the performer does not handle the exception, the exception is automatically thrown        intLength =Array.Length;    System.out.println (length); }

Java exception handling and use of custom exceptions

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.