Exception Handling in Java

Source: Internet
Author: User
Tags finally block getmessage throwable

The following is referenced from http://wiki.jikexueyuan.com/project/java/exceptions.html:

An exception is a problem that occurs during the execution of a program. Causes of the exception include the following points:

    • Invalid data entered by user
    • User opens a file that cannot be found
    • The network connection has been lost or the JVM has exhausted memory

Some exceptions are due to user errors, also due to programmer errors, and because some physical resources are in some form of error.

To understand exception handling in Java, you need to understand the three categories of exceptions:

    • Detect Exception (Checked exceptions): A detected exception is usually a user error or a programmer can not foresee the error, if a file will be opened, but the system cannot find the file, the exception will occur. These exceptions cannot be simply ignored at compile time.
    • Runtime exception (runtime Exceptions): Runtime exceptions can be avoided by program syntax. Unlike detecting exceptions, run-time exceptions can be ignored at compile time.
    • error (Errors): This is not an exception, but this is not something that the user or programmer can control. Errors are often ignored in code because there is almost nothing to do with an error. For example, if a stack overflow occurs, an error will occur. They are also ignored at compile time.

One, the abnormal hierarchy

All exception classes are sub-types of the Java.lang.Exception class. Exception classes are subclasses of the Throwable class. Except for the exception class, the error class is also a subclass produced by the Throwable class.

Errors are generally not resolved by Java programs. These conditions usually occur when a bug is not resolved by the Java program. Errors is used to indicate errors generated by those runtime environments. For example, the JVM (Java Virtual machine) is not in memory. The general program cannot recover from the error.

The exception class contains two subclasses: the IOException class and the RuntimeException class.

Second, the Anomaly method

The following is a list of important methods for the Throwable class.

Method Description
Public String GetMessage () Returns details about the occurrence of an exception, which is initialized in the Throwable constructor
Public Throwable Getcause () Returns the reason that the exception occurred, represented by the Throwable object
Public String toString () Returns the name of the class associated with the result of GetMessage ()
public void Printstacktrace () Prints the result of the stack address of the ToString () trace error output stream.
Public Stacktraceelement [] Getstacktrace () Returns an array that contains the address of each element at the stack. The index of the element 0 represents the top of the call stack, and the last element represents the bottom of the method call stack.
Public Throwable Fillinstacktrace () Populates the stack address of the Throwable object with the current stack address, adding to any previous stack address information.

Third, catch the exception

A method uses the keyword try and catch to catch an exception. A try/catch block is placed outside the code that could produce an exception. The code inside the Try/catch block is protected, and its syntax is as follows:

Try {   //Protected code}catch(Exceptionname E1) {   //  Catch Block}

For the declaration of a catch, you must indicate the type of exception being caught. If an exception occurs in the protected code, the catch block that follows the try is detected. If the exception type appears in the catch, the exception is passed to the catch, as if the argument were passed to the method parameter.


The following example declares an array containing two elements. The code then tries to access the third element of the array, which throws an exception.

//File Name:ExcepTest.javaImportJava.io.*; Public classexceptest{ Public Static voidMain (String args[]) {Try{         intA[] =New int[2]; System.out.println ("Access element Three:" + a[3]); }Catch(arrayindexoutofboundsexception e) {System.out.println ("Exception Thrown:" +e); } System.out.println ("Out of The Block"); }}//this will produce the following resultsException Thrown:java.lang.arrayindexoutofboundsexception:3Out of the block

Four or more catch blocks

A try block can have multiple catch blocks. The syntax for multiple catch blocks is as follows:

Try {   //Protected code}catch(ExceptionType1 E1) {   // Catch Block} Catch (ExceptionType2 E2) {   //catch block}catch(ExceptionType3 e3) {   //Catch block}

The preceding statement shows three catch blocks, but can be followed by any number of catch blocks after a try. When an exception occurs in the protected code, the exception is first caught by the first catch block, and if the exception type is listed in the first catch block, it is captured in the first catch block. If it is not listed, the next catch block is matched in turn until the exception type is found. Finally, regardless of whether the existing method is found, it will stop executing and throw an exception to the stack address of the previous method.


The following is how the code snippet shows how to use multiple Try/catch statements.

Try {   new  FileInputStream (fileName);    = (byte) File.read ();} Catch (IOException i) {   i.printstacktrace ();    return -1;} Catch // Not valid! {   f.printstacktrace ();    return -1;}

Five, throws/throw key words

If a method cannot handle a detection exception, the method must be declared with the keyword throws. The throws keyword appears at the end of the method name.

You can throw an exception by using the keyword throw or instantiate the exception you just caught.

The following method declares that it throws a RemoteException exception:

import java.io.*;  Public class classname{   publicvoid deposit (doublethrows  remoteexception   {      //  Method implementation      throw new  RemoteException ();   }    // remainder of class definition}

A method can declare that more than one exception is thrown, and these exceptions are separated by commas. For example, the following method declarations throw remoteexception and insufficientfundsexception:

import java.io.*;  Public class classname{   publicvoid Withdraw (doublethrows  RemoteException, insufficientfundsexception   {       //  Method implementation    }    // remainder of class definition}

Tip: Throw is used to throw an exception, throws is used to tell the method calling this method needs to handle the exception, the same throws can be called in the method without processing, directly throws to the upper layer, know to the JVM to handle.

Six, the key word finally

The finally keyword is used to create a block of code that follows the try, and the finally code block is always executed, no matter what the exception occurs.

Using the finally block allows you to run any Cleanup-type statement you want to execute, regardless of what happens in the protected code.

The finally code block appears after the last catch block and the syntax is as follows:

Try {   //Protected code}catch(ExceptionType1 E1) {   // Catch Block} Catch (ExceptionType2 E2) {   //catch block}catch(ExceptionType3 e3) {   //Catch block} finally {   //thefinally block always executes.}


 Public classexceptest{ Public Static voidMain (String args[]) {intA[] =New int[2]; Try{System.out.println ("Access element Three:" + a[3]); }Catch(arrayindexoutofboundsexception e) {System.out.println ("Exception Thrown:" +e); }      finally{a[0] = 6; System.out.println ("First element value:" +a[0]); System.out.println ("The finally statement is executed"); }   }}//this will produce the following results:Exception Thrown:java.lang.arrayindexoutofboundsexception:3First element value:6 thefinallyStatement is executed

The following points need to be noted:

    • Catch is not possible without the TRY keyword.
    • A finally block is not enforced in a try/catch statement block.
    • A TRY statement block cannot exist independently (that is, there are no catch and finally blocks).
    • There is no code between the Try/catch and finally blocks.

Vii. declaring your own exceptions

You can create your own exceptions in Java. To write your own exception class, keep in mind the following points:

    • All exceptions must be throwable subclasses.
    • If you want to write a detection exception that automatically adheres to the correct processing or declaration rules, you need to inherit the exception class.
    • If you want to write a run-time exception, you need to inherit the RuntimeException class.

You can define your own exception class as follows:

class extends exception{}

You only need to inherit the exception class to create your own exception class. These are considered to be detection anomalies. The following Insufficientfundsexception class is a user-defined exception that also inherits the exception class and becomes a detection exception. An exception class, like any other class, contains fields and methods.


//File Name Insufficientfundsexception.javaImportJava.io.*; Public classInsufficientfundsexceptionextendsexception{Private Doubleamount;  PublicInsufficientfundsexception (Doubleamount) {       This. Amount =amount; }     Public DoubleGetamount () {returnamount; }}

To demonstrate the use of user-defined exceptions, the following Checkingaccount class contains a withdraw () method that throws a Insufficientfundsexception exception.

//File Name Checkingaccount.javaImportJava.io.*; Public classcheckingaccount{Private Doublebalance; Private intNumber ;  PublicCheckingaccount (intNumber ) {       This. Number =Number ; }    Public voidDepositDoubleamount) {Balance+=amount; }    Public voidWithdraw (DoubleAmountthrowsinsufficientfundsexception {if(Amount <=balance) {Balance-=amount; }      Else      {         Doubleneeds = amount-balance; Throw Newinsufficientfundsexception (needs); }   }    Public DoubleGetBalance () {returnbalance; }    Public intGetNumber () {returnNumber ; }}

The following Bankdemo program shows the deposit () and withdraw () methods that call Checkingaccount.

//File Name Bankdemo.java Public classbankdemo{ Public Static voidmain (String [] args) {Checkingaccount C=NewCheckingaccount (101); System.out.println ("Depositing ..."); C.deposit (500.00); Try{System.out.println ("\nwithdrawing ..."); C.withdraw (100.00); System.out.println ("\nwithdrawing ..."); C.withdraw (600.00); }Catch(insufficientfundsexception e) {System.out.println ("Sorry, but you were short $" +E.getamount ());      E.printstacktrace (); }    }}

Compiling the above three files and running Bankdemo will produce the following results:

Depositing ... Withdrawing $... Withdrawing $ $200.0 insufficientfundsexception at        Checkingaccount.withdraw (Checkingaccount.java:+) at        bankdemo.main (Bankdemo.java:13)

Viii. Common anomalies

In Java, you can define two types of exceptions and errors

    • JVM Exceptions: These exceptions/errors are thrown by the JVM at the logical level or specifically. For example: Nullpointerexception,arrayindexoutofboundsexception,classcastexception.
    • Procedural exceptions: These exceptions are explicitly thrown by the application or programmer who wrote the API, for example: Illegalargumentexception,illegalstateexception.

Test Project: https://github.com/easonjim/5_java_example/tree/master/javabasicstest/test15

Exception Handling 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.