Movatterモバイル変換


[0]ホーム

URL:


Jump to content
WikibooksThe Free Textbook Project
Search

Throwing and Catching Exceptions

75% developed
From Wikibooks, open books for an open world
<Java Programming

ExceptionsJava Programming
Throwing and Catching Exceptions
Checked Exceptions
NavigateExceptions topic:()


Language compilers are adept at pointing out most of the erroneous code in a program, however there are some errors that only become apparent when the program is executed. Consider thecode listing 6.1; here, the program defines a methoddivide that does a simple division operation taking two integers as parameter arguments and returning the result of their division. It can safely be assumed that when thedivide(4, 2) statement is called, it would return the number2. However, consider the next statement, where the program relies upon the provided command line arguments to generate a division operation. What if the user provides the number zero (0) as the second argument? We all know that division by zero is impossible, but the compiler couldn't possibly have anticipated the user providing zero as an argument.

Computer codeCode listing 6.1: SimpleDivisionOperation.java
publicclassSimpleDivisionOperation{publicstaticvoidmain(String[]args){System.out.println(divide(4,2));if(args.length>1){intarg0=Integer.parseInt(args[0]);intarg1=Integer.parseInt(args[1]);System.out.println(divide(arg0,arg1));}}publicstaticintdivide(inta,intb){returna/b;}}
Standard input or outputOutput for Code listing 6.1
$ java SimpleDivisionOperation 1 02Exception in thread "main" java.lang.ArithmeticException: / by zero     at SimpleDivisionOperation.divide(SimpleDivisionOperation.java:12)     at SimpleDivisionOperation.main(SimpleDivisionOperation.java:7)

Suchexceptional code that results in erroneous interpretations at program runtime usually results in errors that are calledexceptions in Java. When the Java interpreter encounters an exceptional code, it halts execution and displays information about the error that occurs. This information is known as astack trace. Thestack trace in the above example tells us more about the error, such as the thread —"main" — where the exception occurred, the type of exception —java.lang.ArithmeticException, a comprehensible display message —/ by zero, and the exact methods and the line numbers where the exception may have occurred.

Exception object

[edit |edit source]

The preceding exception could have been created explicitly by the developer as it is the case in the following code:

Computer codeCode listing 6.2: SimpleDivisionOperation.java
publicclassSimpleDivisionOperation{publicstaticvoidmain(String[]args){System.out.println(divide(4,2));if(args.length>1){// Convert a string to an integerintarg0=Integer.parseInt(args[0]);intarg1=Integer.parseInt(args[1]);System.out.println(divide(arg0,arg1));}}publicstaticintdivide(inta,intb){if(b==0){thrownewArithmeticException("You can\'t divide by zero!");}else{returna/b;}}}
Standard input or outputOutput for Code listing 6.2
$ java SimpleDivisionOperation 1 02Exception in thread "main" java.lang.ArithmeticException: You can't divide by zero!at SimpleDivisionOperation.divide(SimpleDivisionOperation.java:14)at SimpleDivisionOperation.main(SimpleDivisionOperation.java:8)

Note that whenb equals zero, there is no return value. Instead of ajava.lang.ArithmeticException generated by the Java interpreter itself, it is an exception created by the coder. The result is the same. It shows you that an exception is an object. Its main particularity is that it can be thrown. An exception object must inherit fromjava.lang.Exception. Standard exceptions have two constructors:

  1. The default constructor; and,
  2. A constructor taking a string argument so that you can place pertinent information in the exception.
ExampleCode section 6.1: Instance of an exception object with the default constructor.
newException();
ExampleCode section 6.2: Instance of anException object by passing string in constructor.
newException("Something unexpected happened");

This string can later be extracted using various methods, as you can see in thecode listing 6.2.

You can throw any type ofThrowable object using the keywordthrow. It interrupts the method. Anything after thethrow statement would not be executed, unless thethrown exception ishandled. The exception object is notreturned from the method, it isthrown from the method. That means that the exception object is not the return value of the method and the calling method can be interrupted too and so on and so on...

Typically, you'll throw a different class of exception for each different type of error. The information about the error is represented both inside the exception object and implicitly in the name of the exception class, so someone in the bigger context can figure out what to do with your exception. Often, the only information is the type of exception, and nothing meaningful is stored within the exception object.

Oracle standard exception classes

[edit |edit source]

The box 6.1 below talks about the various exception classes within thejava.lang package.

Box 6.1: The Java exception classes

Throwable
The Throwable class is the superclass of all errors and exceptions in the Java language. Only objects that are instances of this class (or one of its subclasses) are thrown by the Java Virtual Machine or can be thrown by the Java throw statement.
A throwable contains a snapshot of the execution stack of its thread at the time it was created. It can also contain a message string that gives more information about the error. Finally, it can contain a cause: another throwable that caused this throwable to get thrown. The cause facility was added in release 1.4. It is also known as the chained exception facility, as the cause can, itself, have a cause, and so on, leading to a "chain" of exceptions, each caused by another.
Error
An Error indicates serious problems that a reasonable application should not try to handle. Most such errors are abnormal conditions.
Exception
The class Exception and its subclasses are a form of Throwable that indicates conditions that a reasonable application might want to handle. Also this is the class that a programmer may want to extend when adding business logic exceptions.
RuntimeException
RuntimeException is the superclass of those exceptions that can be thrown during the normal operation of the Java Virtual Machine. A method is not required to declare its throws clause in any subclasses of RuntimeException that might be thrown during the execution of the method but not caught.
Figure 6.2: The exception classes and their inheritance model in the JCL.

try/catch statement

[edit |edit source]

Try/Catch is straight up better.By default, when an exception is thrown, the current method is interrupted, the calling method is interrupted too and so on till themain method. A thrown exception can also be caught using atry/catch statement. Below is how atry/catch statement works:

ExampleCode section 6.3: Division into atry block.
inta=4;intb=2;intresult=0;try{intc=a/b;result=c;}catch(ArithmeticExceptionex){result=0;}returnresult;

The executed code lines have been highlighted. When no exception is thrown, the method flow executes thetry statement and not thecatch statement.

ExampleCode section 6.4: Catching 'division by zero' errors.
inta=4;intb=0;intresult=0;try{intc=a/b;result=c;}catch(ArithmeticExceptionex){result=0;}returnresult;

As there is a thrown exception at line 5, the line 6 is not executed, but the exception is caught by thecatch statement so thecatch block is executed. The following code is also executed. Note that thecatch statement takes an exception as parameter. There is a third case: when the exception is not from the same class as the parameter:

ExampleCode section 6.5: Uncaught exception.
inta=4;intb=0;intresult=0;try{intc=a/b;result=c;}catch(NullPointerExceptionex){result=0;}returnresult;

It is as if there is notry/catch statement. The exception is thrown to the calling method.

catch blocks

[edit |edit source]

Atry/catch statement can contain severalcatch blocks, to handle different exceptions in different ways. Eachcatch block must take a parameter of a different throwable class. A thrown object may match severalcatch block but only the firstcatch block that matches the object will be executed. A catch-block will catch a thrown exception if and only if:

  • the thrown exception object is the same as the exception object specified by the catch-block.
  • the thrown exception object is the subtype of the exception object specified by the catch-block.

This means that thecatch block order is important. As a consequence, you can't put acatch block that catches all the exception (which take ajava.lang.Exception as parameter) before acatch block that catches a more specific exception as the second block could never be executed.

ExampleCode section 6.6: Exception handling with catch blocks.
try{// Suppose the code here throws any exceptions,// then each is handled in a separate catch block.int[]tooSmallArray=newint[2];intoutOfBoundsIndex=10000;tooSmallArray[outOfBoundsIndex]=1;System.out.println("No exception thrown.");}catch(NullPointerExceptionex){System.out.println("Exception handling code for the NullPointerException.");}catch(NumberFormatExceptionex){System.out.println("Exception handling code for the NumberFormatException.");}catch(ArithmeticException|IndexOutOfBoundsExceptionex){System.out.println("Exception handling code for ArithmeticException"+" or IndexOutOfBoundsException.");}catch(Exceptionex){System.out.println("Exception handling code for any other Exception.");}
Standard input or outputOutput for Code section 6.6
Exception handling code for ArithmeticException or IndexOutOfBoundsException.

At line 14, we use amulti-catch clause. It is available since the JDK 7. This is a combination of severalcatch clauses and let's you handle exceptions in a single handler while also maintaining their types. So, instead of being boxed into a parent Exception super-class, they retain their individual types.

You can also use thejava.lang.Throwable class here, sinceThrowable is the parent class for theapplication-specificException classes. However, this is discouraged in Java programming circles. This is becauseThrowable happens to also be the parent class for thenon-application specificError classes which are not meant to be handled explicitly as they are catered for by the JVM itself.

finally block

[edit |edit source]

Afinally block can be added after thecatch blocks. Afinally block is always executed, even when no exception is thrown, an exception is thrown and caught, or an exception is thrown and not caught. It's a place to put code that should always be executed after an unsafe operation like a file close or a database disconnection. You can define atry block withoutcatch block, however, in this case, it must be followed by afinally block.

Example of handling exceptions

[edit |edit source]

Let's examine the following code:

WarningCode section 6.7: Handling exceptions.
publicvoidmethodA()throwsSomeException{// Method body}publicvoidmethodB()throwsCustomException,AnotherException{// Method body}publicvoidmethodC(){methodB();methodA();}

In thecode section 6.7,methodC is invalid. BecausemethodA andmethodB pass (or throw) exceptions,methodC must be prepared to handle them. This can be handled in two ways: atry-catch block, which will handle the exception within the method and athrows clause which would in turn throw the exception to the caller to handle. The above example will cause a compilation error, as Java is very strict about exception handling. So the programmer is forced to handle any possible error condition at some point.

A method can do two things with an exception: ask the calling method to handle it by thethrows declaration or handle the exception inside the method by thetry-catch block.

To work correctly, the original code can be modified in multiple ways. For example, the following:

ExampleCode section 6.8: Catching and throwing exceptions.
publicvoidmethodC()throwsCustomException,SomeException{try{methodB();}catch(AnotherExceptione){// Handle caught exceptions.}methodA();}

TheAnotherException frommethodB will be handled locally, whileCustomException andSomeException will be thrown to the caller to handle it. Most of the developers are embarrassed when they have to choose between the two options. This type of decision should not be taken at development time. If you are a development team, it should be discussed between all the developers in order to have a common exception handling policy.

Keyword references

[edit |edit source]


Clipboard

To do:
Add some exercises like the ones inVariables


ExceptionsJava Programming
Throwing and Catching Exceptions
Checked Exceptions
Retrieved from "https://en.wikibooks.org/w/index.php?title=Java_Programming/Throwing_and_Catching_Exceptions&oldid=3967501"
Category:
Hidden category:

[8]ページ先頭

©2009-2025 Movatter.jp