java AddTwoIntegersException Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 0 at AddTwoIntegersException.main(AddTwoIntegersException.java:5) > java AddTwoIntegersException A B Exception in thread "main" java.lang.NumberFormatException: For input string: "A" at java.lang.NumberFormatException.forInputString(NumberFormatException. java:48) at java.lang.Integer.parseInt(Integer.java:468) at java.lang.Integer.parseInt(Integer.java:518) at AddTwoIntegersException.main(AddTwoIntegersException.java:5)"> java AddTwoIntegersException Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 0 at AddTwoIntegersException.main(AddTwoIntegersException.java:5) > java AddTwoIntegersException A B Exception in thread "main" java.lang.NumberFormatException: For input string: "A" at java.lang.NumberFormatException.forInputString(NumberFormatException. java:48) at java.lang.Integer.parseInt(Integer.java:468) at java.lang.Integer.parseInt(Integer.java:518) at AddTwoIntegersException.main(AddTwoIntegersException.java:5)">
Download presentation
Presentation is loading. Please wait.
1
Chapter 10 – Exception Handling
What is an Exception? An exception is an event that occurs during the execution of a program which interrupts the normal flow of instructions. Examples - Divide a number by 0 Access an out-of-bounds array element Null Pointer reference Cannot convert a string to an integer .... and lots more.
2
Example > java AddTwoIntegersException
public class AddTwoIntegersException { public static void main( String args[] ) { int num1, num2; num1 = Integer.parseInt(args[0]); num2 = Integer.parseInt(args[1]); System.out.println("The sum is " + (num1+num2)); } > java AddTwoIntegersException Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 0 at AddTwoIntegersException.main(AddTwoIntegersException.java:5) > java AddTwoIntegersException A B Exception in thread "main" java.lang.NumberFormatException: For input string: "A" at java.lang.NumberFormatException.forInputString(NumberFormatException. java:48) at java.lang.Integer.parseInt(Integer.java:468) at java.lang.Integer.parseInt(Integer.java:518) at AddTwoIntegersException.main(AddTwoIntegersException.java:5)
3
How Java Handles Exception?
When an error occurs within a Java method, the method creates an Exception object and hands it off to the runtime system. The runtime system is then responsible for finding some code to handle the error. In Java terminology, creating an exception object and handing it to the runtime system is called throwing an exception. After a method throws an exception, the runtime system will find someone to handle the exception.
4
How Java Handles Exception?
void p() { try { f(); } catch (Exception e) { // something to do ..... void f() { g(); void g() { h(); void h() { // error occurs throw new Exception(); ...... The runtime system searches backwards through the call stack to find a method that contains an appropriate exception handler (see example at the right). The exception handler chosen is said to catch the exception. If no exception handler is found, the Java program terminates . 3 2 1
5
Throwing an Exception Handle Exception
When an error occurs within a Java method, the method calls the throw statement to Indicates an exception has occurred. if (total < 0) throw new Exception("Negative Total"); Handle Exception Some exceptions (examples will be shown in next lecture) must be handled. Exception can be handled in a method in two ways: 1. Use a try-catch block to handle the exception 2. Rethrow the exception
6
try Blocks The try block structure try { statements that may throw an exception } catch ( ExceptionType1 exceptionReference1 ) { statements to process an exception } catch ( ExceptionType2 exceptionReference2 ) { statements to process an exception } finally { statements always executed } A try followed by one or more of catch blocks finally block is optional Optional
7
Basics of Java Exception Handling
Code that could generate errors put in try blocks Code for error handling enclosed in a catch block The finally always executes with or without an error
8
Example 1 public class CatchException1 {
public static void main( String args[] ) { int num1, num2; try { num1 = Integer.parseInt(args[0]); num2 = Integer.parseInt(args[1]); System.out.println("The sum is " + (num1+num2)); } catch (ArrayIndexOutOfBoundsException e) { System.out.println("Invalid Number of arguments!"); System.out.println( "Usage : java AddTwoIntegers <num1> <num2>"); catch (NumberFormatException e) { System.out.println("Please enter integers!"); finally { System.out.println("Thank you for using this program."); >java CatchException1 Invalid Number of arguments! Usage : java AddTwoIntegers <num1> <num2> Thank you for using this program.
9
NumberFormatException ArrayIndexOutOfBoundsException
Example 1 >java CatchException1 A B Please enter integers! Usage : java AddTwoIntegers <num1> <num2> Thank you for using this program. >java CatchException The sum is 46 Thank you for using this program. Example 2 Single catch can handle multiple exceptions The catch statement in the next example catches exception objects of Exception and all its subclasses. Exception NumberFormatException ArrayIndexOutOfBoundsException
10
Message stored in the Exception object e
Example 2 public class CatchException2 { public static void main( String args[] ) { int num1, num2; try { num1 = Integer.parseInt(args[0]); num2 = Integer.parseInt(args[1]); System.out.println("The sum is " + (num1+num2)); } catch (Exception e) { System.out.println("The error : " + e.toString()); System.out.println( "Usage : java AddTwoIntegers <num1> <num2>"); Message stored in the Exception object e >java CatchException2 The error : java.lang.ArrayIndexOutOfBoundsException: 0 Usage : java AddTwoIntegers <num1> <num2> >java CatchException2 A B The error : java.lang.NumberFormatException: For input string: "A" Usage : java AddTwoIntegers <num1> <num2>
11
Throwing an Exception The throw statement is executed to indicate that an exception has occurred. This is called throwing an exception. Example class ComplexNum { private double real; private double imag; public ComplexNum (double r, double i) { real = r; imag = i; } public ComplexNum divide(double d) throws Exception { if (d == 0.0) throw new Exception( "Attempted divide by zero in ComplexNum.divide"); return new ComplexNum(real/d, imag/d);
12
Throwing an Exception Note : The phrase throws Exception must be appended to the method header of divide to indicate that an object of Exception (or its subclass) may be thrown by the method. Otherwise the program cannot be compiled. class ComplexNum { private double real; private double imag; public ComplexNum Divide(double d) { if (d == 0.0) throw new Exception( "Attempted divide by zero in ComplexNum.divide"); return new ComplexNum(real/d, imag/d); } forgot to put throws Exception >javac ComplexNum.java ComplexNum.java:7: unreported exception java.lang.Exception; must be caught or declared to be thrown throw new Exception( ^ 1 error
13
throws Clause Lists the exceptions thrown by a method int functionName( paramterList ) throws ExceptionType1, ExceptionType2,… { // method body } RuntimeExceptions occur during execution ArrayIndexOutOfBoundsException NullPointerException too common Do not need to catch or rethrow - NOT a syntax error. But you must handle (either catch or rethrow) the Exception objects that are not created from the subclasses of RuntimeException - See the previous example.
14
Example 1 public class UsingExceptions1 {
public static void main( String args[] ) { try { throwException(); } catch ( Exception exception ) { System.err.println( "Exception handled in main" ); public static void throwException() throws Exception { // throw an exception and immediately catch it System.out.println( "Method throwException" ); throw new Exception(); // generate exception System.err.println( "Exception handled in method throwException" ); throw exception; // rethrow for further processing finally { "Finally executed in throwException" ); >java UsingExceptions1 Method throwException Exception handled in method throwException Finally executed in throwException Exception handled in main
15
Example 2 public class UsingExceptions2 {
public static void main( String args[] ) { try { throwException(); } catch ( Exception exception ) { System.err.println( "Exception handled in main" ); public static void throwException() throws Exception { // throw an exception and catch it in main System.out.println( "Method throwException" ); throw new Exception(); // generate exception catch( RuntimeException runtimeException ) { System.err.println( "Exception handled in method throwException" ); finally { System.err.println( "Finally is always executed" ); >java UsingExceptions2 Method throwException Finally is always executed Exception handled in main
16
Why using Exceptions? Standardized error handling policy. Separate error handling from the logic flow (no if-else statement). Force the programmer to handle the error. Can be used in Constructor.
17
Exception objects have several member methods, including:
public void printStackTrace() Print a stack trace --- a list that shows the sequence of method calls up to this exception. public String getMessage() Return a string that may describe what went wrong.
18
Example 3 public class UsingExceptions3 {
public static void main( String args[] ) { try { throwException(); } catch ( Exception e ) { System.err.println( "Exception handled in main" ); System.err.println( "Exception:" + e.getMessage() ); System.err.println( "Stack Trace: "); e.printStackTrace(); public static void throwException() throws Exception { System.out.println( "Method throwException" ); throw new Exception("My message"); >java UsingExceptions3 Method throwException Exception handled in main Exception:My message Stack Trace: java.lang.Exception: My message at UsingExceptions3.throwException(UsingExceptions3.java:16) at UsingExceptions3.main(UsingExceptions3.java:4)
19
How to write your own Exception
You can write your own Exception class: The class should extend Exception (or its subclass) Pass the error message (string) to the superclass' constructor. class MyException extends Exception { public MyException() { super("The error message comes here"); }
20
How to write your own Exception
class Main { public static void main(String s[]) { try { f(); } catch (MyException e) { System.out.println("Exception Caught: " + e); public static void f() throws MyException{ throw new MyException(); Output Exception Caught: MyException: The error message comes here
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.