SlideShare a Scribd company logo
Java Exception
   Handling

                 1
Topics
●   What is an Exception?
●   What happens when an Exception occurs?
●   Benefits of Exception Handling framework
●   Catching exceptions with try-catch
●   Catching exceptions with finally
●   Throwing exceptions
●   Rules in exception handling
●   Exception class hierarchy
●   Checked exception and unchecked exception
●   Creating your own exception class
●   Assertions                                  2
What is an
Exception?
             3
What is an Exception?
●   Exceptional event
●   Error that occurs during runtime
●   Cause normal program flow to be disrupted
●   Examples
    –   Divide by zero errors
    –   Accessing the elements of an array beyond its range
    –   Invalid input
    –   Hard disk crash
    –   Opening a non-existent file
    –   Heap memory exhausted
                                                              4
Exception Example
1   class DivByZero {
2       public static void main(String args[]) {
3           System.out.println(3/0);
4           System.out.println(“Pls. print me.”);
5       }
6   }




                                                    5
Example: Default Exception
                Handling
●   Displays this error message
    Exception in thread "main"
      java.lang.ArithmeticException: / by zero
          at DivByZero.main(DivByZero.java:3)
●   Default exception handler
    –   Provided by Java runtime
    –   Prints out exception description
    –   Prints the stack trace
         ●   Hierarchy of methods where the exception occurred
    –   Causes the program to terminate

                                                                 6
What Happens When
an Exception Occurs?
                       7
What Happens When an Exception
           Occurs?
●   When an exception occurs within a method, the
    method creates an exception object and hands it off
    to the runtime system
    –   Creating an exception object and handing it to the
        runtime system is called “throwing an exception”
    –   Exception object contains information about the error,
        including its type and the state of the program when the
        error occurred




                                                                   8
What Happens When an Exception
           Occurs?
●
    The runtime system searches the call stack
    for a method that contains an exception
    handler




                                                 9
What Happens When an Exception
           Occurs?
●   When an appropriate handler is found, the runtime
    system passes the exception to the handler
    –   An exception handler is considered appropriate if the
        type of the exception object thrown matches the type that
        can be handled by the handler
    –   The exception handler chosen is said to catch the
        exception.
●   If the runtime system exhaustively searches all the
    methods on the call stack without finding an
    appropriate exception handler, the runtime system
    (and, consequently, the program) terminates and
    uses the default exception handler
                                                                    10
Searching the Call Stack for
   an Exception Handler




                               11
Benefits of Exception
Handling Framework
                        12
Benefits of Java Exception
         Handling Framework
●   Separating Error-Handling code from “regular”
    business logic code
●   Propagating errors up the call stack
●   Grouping and differentiating error types




                                                    13
Separating Error Handling Code
          from Regular Code
●   In traditional programming, error detection,
    reporting, and handling often lead to confusing
    spaghetti code
●   Consider pseudocode method here that reads an
    entire file into memory
    readFile {
      open the file;
      determine its size;
      allocate that much memory;
      read the file into memory;
      close the file;
    }
                                                      14
Traditional Programming: No
    separation of error handling code
●   In traditional programming, To handle such cases,
    the readFile function must have more code to do
    error detection, reporting, and handling.
     errorCodeType readFile {
        initialize errorCode = 0;

       open the file;
       if (theFileIsOpen) {
           determine the length of the file;
           if (gotTheFileLength) {
               allocate that much memory;
               if (gotEnoughMemory) {
                   read the file into memory;
                   if (readFailed) {
                       errorCode = -1;
                   }
               } else {
                   errorCode = -2;                      15
               }
Traditional Programming: No
separation of error handling code
●



           } else {
               errorCode = -3;
           }
           close the file;
           if (theFileDidntClose && errorCode == 0) {
               errorCode = -4;
           } else {
               errorCode = errorCode and -4;
           }
        } else {
           errorCode = -5;
        }
        return errorCode;
    }

                                                        16
Separating Error Handling Code
          from Regular Code
●   Exceptions enable you to write the main flow of
    your code and to deal with the exceptional cases
    elsewhere
     readFile {
       try {
          open the file;
          determine its size;
          allocate that much memory;
          read the file into memory;
          close the file;
       } catch (fileOpenFailed) {
         doSomething;
       } catch (sizeDeterminationFailed) {
          doSomething;
       } catch (memoryAllocationFailed) {
          doSomething;
       } catch (readFailed) {
          doSomething;
       } catch (fileCloseFailed) {
          doSomething;
                                                       17
       }
     }
Separating Error Handling Code
          from Regular Code
●   Note that exceptions don't spare you the effort of
    doing the work of detecting, reporting, and handling
    errors, but they do help you organize the work more
    effectively.




                                                       18
Propagating Errors Up the Call Stack
●   Suppose that the readFile method is the fourth method in a
    series of nested method calls made by the main program:
    method1 calls method2, which calls method3, which finally
    calls readFile
●   Suppose also that method1 is the only method interested in
    the errors that might occur within readFile.
     method1 {
       call method2;
     }

     method2 {
       call method3;
     }

     method3 {
       call readFile;
     }                                                           19
Traditional Way of Propagating Errors
method1 {                    ●
                                 Traditional error-
    errorCodeType error;
    error = call method2;        notification techniques
    if (error)                   force method2 and
        doErrorProcessing;
    else                         method3 to propagate
}
        proceed;                 the error codes returned
                                 by readFile up the call
errorCodeType method2 {
  errorCodeType error;
                                 stack until the error
  error = call method3;          codes finally reach
  if (error)
      return error;              method1—the only
  else                           method that is
      proceed;
}                                interested in them.
errorCodeType method3 {
  errorCodeType error;
  error = call readFile;
  if (error)
      return error;
  else                                                      20
      proceed;
Using Java Exception Handling
method1 {
    try {                     ●
                                  A method can duck any
        call method2;             exceptions thrown
    } catch (exception e) {       within it, thereby
        doErrorProcessing;        allowing a method
    }                             farther up the call stack
}                                 to catch it. Hence, only
                                  the methods that care
method2 throws exception {        about errors have to
    call method3;                 worry about detecting
}                                 errors
                              ●
                                  Any checked exceptions
method3 throws exception {
                                  that can be thrown
    call readFile;
                                  within a method must
}
                                  be specified in its
                                  throws clause.              21
Grouping and Differentiating Error
             Types
●   Because all exceptions thrown within a program are
    objects, the grouping or categorizing of exceptions
    is a natural outcome of the class hierarchy
●   An example of a group of related exception classes
    in the Java platform are those defined in java.io —
    IOException and its descendants
    –   IOException is the most general and represents any type
        of error that can occur when performing I/O
    –   Its descendants represent more specific errors. For
        example, FileNotFoundException means that a file could
        not be located on disk.

                                                                  22
Grouping and Differentiating Error
             Types
●   A method can write specific handlers that can
    handle a very specific exception
●   The FileNotFoundException class has no
    descendants, so the following handler can handle
    only one type of exception.

    catch (FileNotFoundException e) {
        ...
    }


                                                       23
Grouping and Differentiating Error
             Types
●   A method can catch an exception based on its
    group or general type by specifying any of the
    exception's superclasses in the catch statement.
    For example, to catch all I/O exceptions, regardless
    of their specific type, an exception handler specifies
    an IOException argument.

    // Catch all I/O exceptions, including
    // FileNotFoundException, EOFException, and so on.
    catch (IOException e) {
        ...
                                                         24
    }
Catching Exceptions
   with try-catch
                      25
Catching Exceptions:
          The try-catch Statements
●   Syntax:
    try {
        <code to be monitored for exceptions>
    } catch (<ExceptionType1> <ObjName>) {
        <handler if ExceptionType1 occurs>
    }
    ...
    } catch (<ExceptionTypeN> <ObjName>) {
        <handler if ExceptionTypeN occurs>
    }


                                                26
Catching Exceptions:
             The try-catch Statements
1    class DivByZero {
2        public static void main(String args[]) {
3            try {
4                System.out.println(3/0);
5                System.out.println(“Please print me.”);
6            } catch (ArithmeticException exc) {
7                //Division by zero is an ArithmeticException
8                System.out.println(exc);
9            }
10           System.out.println(“After exception.”);
11       }
12   }
                                                                27
Catching Exceptions:
                    Multiple catch
1    class MultipleCatch {
2        public static void main(String args[]) {
3            try {
4                 int den = Integer.parseInt(args[0]);
5                 System.out.println(3/den);
6            } catch (ArithmeticException exc) {
7                 System.out.println(“Divisor was 0.”);
8            } catch (ArrayIndexOutOfBoundsException exc2) {
9                 System.out.println(“Missing argument.”);
10           }
11           System.out.println(“After exception.”);
12       }
13   }                                                         28
Catching Exceptions:
                 Nested try's
class NestedTryDemo {
   public static void main(String args[]){
      try {
         int a = Integer.parseInt(args[0]);
         try {
              int b = Integer.parseInt(args[1]);
              System.out.println(a/b);
         } catch (ArithmeticException e) {
              System.out.println(“Div by zero error!");
         }
         //continued...

                                                          29
Catching Exceptions:
                 Nested try's
        } catch (ArrayIndexOutOfBoundsException) {
            System.out.println(“Need 2 parameters!");
        }
    }
}




                                                        30
Catching Exceptions:
      Nested try's with methods
1    class NestedTryDemo2 {
2       static void nestedTry(String args[]) {
3           try {
4               int a = Integer.parseInt(args[0]);
5               int b = Integer.parseInt(args[1]);
6               System.out.println(a/b);
7           } catch (ArithmeticException e) {
8               System.out.println("Div by zero error!");
9           }
10      }
11   //continued...
                                                            31
Catching Exceptions:
         Nested try's with methods
12       public static void main(String args[]){
13           try {
14               nestedTry(args);
15           } catch (ArrayIndexOutOfBoundsException e) {
16               System.out.println("Need 2 parameters!");
17           }
18       }
19   }




                                                             32
Catching Exceptions
    with finally
                      33
Catching Exceptions:
               The finally Keyword
●   Syntax:
    try {
        <code to be monitored for exceptions>
    } catch (<ExceptionType1> <ObjName>) {
        <handler if ExceptionType1 occurs>
    } ...
    } finally {
        <code to be executed before the try block ends>
    }
●   Contains the code for cleaning up after a try or a
    catch
                                                          34
Catching Exceptions:
                 The finally Keyword
●   Block of code is always executed despite of
    different scenarios:
    –   Forced exit occurs using a return, a continue or a break
        statement
    –   Normal completion
    –   Caught exception thrown
         ●   Exception was thrown and caught in the method
    –   Uncaught exception thrown
         ●   Exception thrown was not specified in any catch block in
             the method


                                                                        35
Catching Exceptions:
              The finally Keyword
1    class FinallyDemo {
2       static void myMethod(int n) throws Exception{
3          try {
4             switch(n) {
5                  case 1: System.out.println("1st case");
6                           return;
7                  case 3: System.out.println("3rd case");
8                           throw new RuntimeException("3!");
9                  case 4: System.out.println("4th case");
10                          throw new Exception("4!");
11                 case 2: System.out.println("2nd case");
12            }
13   //continued...                                             36
Catching Exceptions:
                 The finally Keyword
14          } catch (RuntimeException e) {
15                System.out.print("RuntimeException: ");
16                System.out.println(e.getMessage());
17          } finally {
18                System.out.println("try-block entered.");
19          }
20      }
21   //continued...




                                                              37
Catching Exceptions:
                  The finally Keyword
22       public static void main(String args[]){
23           for (int i=1; i<=4; i++) {
24               try {
25                   FinallyDemo.myMethod(i);
26               } catch (Exception e){
27                   System.out.print("Exception caught: ");
28                   System.out.println(e.getMessage());
29               }
30               System.out.println();
31           }
32       }
33   }
                                                               38
Throwing
Exceptions

             39
Throwing Exceptions:
              The throw Keyword
●   Java allows you to throw exceptions (generate
    exceptions)
    throw <exception object>;
●   An exception you throw is an object
    –   You have to create an exception object in the same way
        you create any other object
●   Example:
    throw new ArithmeticException(“testing...”);




                                                                 40
Example: Throwing Exceptions

1    class ThrowDemo {
2       public static void main(String args[]){
3          String input = “invalid input”;
4          try {
5             if (input.equals(“invalid input”)) {
6                throw new RuntimeException("throw demo");
7             } else {
8                System.out.println(input);
9             }
10            System.out.println("After throwing");
11         } catch (RuntimeException e) {
12            System.out.println("Exception caught:" + e);
13         }
14      }
15   }
                                                             41
Rules in Exception
    Handling

                     42
Rules on Exceptions
●   A method is required to either catch or list all
    exceptions it might throw
    –   Except for Error or RuntimeException, or their
        subclasses
●   If a method may cause an exception to occur but
    does not catch it, then it must say so using the
    throws keyword
    –   Applies to checked exceptions only
●   Syntax:
    <type> <methodName> (<parameterList>)
      throws <exceptionList> {
         <methodBody>
                                                         43
    }
Example: Method throwing an
                  Exception
1    class ThrowingClass {
2        static void meth() throws ClassNotFoundException {
3            throw new ClassNotFoundException ("demo");
4        }
5    }
6    class ThrowsDemo {
7        public static void main(String args[]) {
8            try {
9                ThrowingClass.meth();
10           } catch (ClassNotFoundException e) {
11               System.out.println(e);
12           }
13       }
                                                              44
14   }
Exception Class
  Hierarchy

                  45
The Error and Exception Classes
●   Throwable class
    –   Root class of exception classes
    –   Immediate subclasses
         ●   Error
         ●   Exception
●   Exception class
    –   Conditions that user programs can reasonably deal with
    –   Usually the result of some flaws in the user program
        code
    –   Examples
         ●   Division by zero error
         ●   Array out-of-bounds error                           46
The Error and Exception Classes
●   Error class
    –   Used by the Java run-time system to handle errors
        occurring in the run-time environment
    –   Generally beyond the control of user programs
    –   Examples
         ●   Out of memory errors
         ●   Hard disk crash




                                                            47
Exception Classes and Hierarchy




                                  48
Exception Classes and Hierarchy
●    Multiple catches should be ordered from subclass
     to superclass.
1    class MultipleCatchError {
2        public static void main(String args[]){
3            try {
4                int a = Integer.parseInt(args [0]);
5                int b = Integer.parseInt(args [1]);
6                System.out.println(a/b);
7            } catch (Exception ex) {
8            } catch (ArrayIndexOutOfBoundsException e) {
9            }
10       }
11   }                                                      49
Checked Exceptions &
Unchecked Exceptions

                       50
Checked and Unchecked
                  Exceptions
●   Checked exception
    –   Java compiler checks if the program either catches or lists the
        occurring checked exception
    –   If not, compiler error will occur
●   Unchecked exceptions
    –   Not subject to compile-time checking for exception handling
    –   Built-in unchecked exception classes
         ● Error
         ● RuntimeException


         ● Their subclasses


    –   Handling all these exceptions may make the program cluttered
        and may become a nuisance
                                                                          51
Creating Your Own
 Exception Class

                    52
Creating Your Own Exception
                   Class
●   Steps to follow
    –   Create a class that extends the RuntimeException or the
        Exception class
    –   Customize the class
            ●   Members and constructors may be added to the class
●   Example:
    1   class HateStringExp extends RuntimeException {
    2           /* some code */
    3   }


                                                                     53
How To Use Your Own Exceptions
 1    class TestHateString {
 2        public static void main(String args[]) {
 3            String input = "invalid input";
 4               try {
 5                   if (input.equals("invalid input")) {
 6                       throw new HateStringExp();
 7                   }
 8                   System.out.println("Accept string.");
 9               } catch (HateStringExp e) {
 10                  System.out.println("Hate string!”);
 11              }
 12       }
                                                             54
 13   }
Assertions

             55
What are Assertions?
●   Allow the programmer to find out if an assumption
    was met
    –   Example: month
●   Extension of comments wherein the assert
    statement informs the person reading the code that
    a particular condition should always be satisfied
    –   Running the program informs you if assertions made are
        true or not
    –   If an assertion is not true, an AssertionError is thrown
●   User has the option to turn it off or on at runtime

                                                                   56
Enabling or Disabling Assertions
●   Program with assertions may not work properly if
    used by clients not aware that assertions were
    used in the code
●   Compiling
     –   With assertion feature:
          javac –source 1.4 MyProgram.java
     –   Without the assertion feature:
          javac MyProgram.java
●   Enabling assertions:
     –   Use the –enableassertions or –ea switch.
          java –enableassertions MyProgram

                                                       57
Assert Syntax
●   Two forms:
    –   Simpler form:
         assert <expression1>;
         where
         ●   <expression1> is the condition asserted to be true
    –   Other form:
         assert <expression1> : <expression2>;
         where
         ●   <expression1> is the condition asserted to be true
         ●   <expression2> is some information helpful in diagnosing why the statement failed




                                                                                                58
Assert Syntax
1    class AgeAssert {
2        public static void main(String args[]) {
3            int age = Integer.parseInt(args[0]);
4            assert(age>0);
5            /* if age is valid (i.e., age>0) */
6            if (age >= 18) {
7                System.out.println(“You're an adult! =)”);
8            }
9        }
10   }



                                                              59
Thank You!


             60

More Related Content

What's hot

14 exception handling
14 exception handling14 exception handling
14 exception handling
jigeno
 
Exception Handling in C++
Exception Handling in C++Exception Handling in C++
Exception Handling in C++
Deepak Tathe
 
Exception Handling in the C++ Constructor
Exception Handling in the C++ ConstructorException Handling in the C++ Constructor
Exception Handling in the C++ Constructor
Somenath Mukhopadhyay
 
Exception handling c++
Exception handling c++Exception handling c++
Exception handling c++
Jayant Dalvi
 
Handling Exceptions In C &amp; C++[Part A]
Handling Exceptions In C &amp; C++[Part A]Handling Exceptions In C &amp; C++[Part A]
Handling Exceptions In C &amp; C++[Part A]
ppd1961
 
7.error management and exception handling
7.error management and exception handling7.error management and exception handling
7.error management and exception handling
Deepak Sharma
 
Exceptions in java
Exceptions in javaExceptions in java
Exceptions in java
JasmeetSingh326
 
Exeption handling
Exeption handlingExeption handling
Java - Exception Handling Concepts
Java - Exception Handling ConceptsJava - Exception Handling Concepts
Java - Exception Handling Concepts
Victer Paul
 
Java Exception handling
Java Exception handlingJava Exception handling
Java Exception handling
kamal kotecha
 
Exception handling
Exception handlingException handling
Exception handling
pooja kumari
 
What is Exception Handling?
What is Exception Handling?What is Exception Handling?
What is Exception Handling?
Syed Bahadur Shah
 
Exception handling and templates
Exception handling and templatesException handling and templates
Exception handling and templates
farhan amjad
 
Unit 5 Java
Unit 5 JavaUnit 5 Java
Unit 5 Java
arnold 7490
 
Java exception
Java exception Java exception
Java exception
Arati Gadgil
 
Exception handling
Exception handlingException handling
Exception handling
Tata Consultancy Services
 
Exception handling
Exception handlingException handling
Exception handling
Shashwat Shriparv
 
Exception handling
Exception handlingException handling
Exception handling
Pranali Chaudhari
 
Exception handling in java
Exception handling in javaException handling in java
Exception handling in java
Pratik Soares
 
Java căn bản - Chapter8
Java căn bản - Chapter8Java căn bản - Chapter8
Java căn bản - Chapter8
Vince Vo
 

What's hot (20)

14 exception handling
14 exception handling14 exception handling
14 exception handling
 
Exception Handling in C++
Exception Handling in C++Exception Handling in C++
Exception Handling in C++
 
Exception Handling in the C++ Constructor
Exception Handling in the C++ ConstructorException Handling in the C++ Constructor
Exception Handling in the C++ Constructor
 
Exception handling c++
Exception handling c++Exception handling c++
Exception handling c++
 
Handling Exceptions In C &amp; C++[Part A]
Handling Exceptions In C &amp; C++[Part A]Handling Exceptions In C &amp; C++[Part A]
Handling Exceptions In C &amp; C++[Part A]
 
7.error management and exception handling
7.error management and exception handling7.error management and exception handling
7.error management and exception handling
 
Exceptions in java
Exceptions in javaExceptions in java
Exceptions in java
 
Exeption handling
Exeption handlingExeption handling
Exeption handling
 
Java - Exception Handling Concepts
Java - Exception Handling ConceptsJava - Exception Handling Concepts
Java - Exception Handling Concepts
 
Java Exception handling
Java Exception handlingJava Exception handling
Java Exception handling
 
Exception handling
Exception handlingException handling
Exception handling
 
What is Exception Handling?
What is Exception Handling?What is Exception Handling?
What is Exception Handling?
 
Exception handling and templates
Exception handling and templatesException handling and templates
Exception handling and templates
 
Unit 5 Java
Unit 5 JavaUnit 5 Java
Unit 5 Java
 
Java exception
Java exception Java exception
Java exception
 
Exception handling
Exception handlingException handling
Exception handling
 
Exception handling
Exception handlingException handling
Exception handling
 
Exception handling
Exception handlingException handling
Exception handling
 
Exception handling in java
Exception handling in javaException handling in java
Exception handling in java
 
Java căn bản - Chapter8
Java căn bản - Chapter8Java căn bản - Chapter8
Java căn bản - Chapter8
 

Viewers also liked

17 exceptions
17   exceptions17   exceptions
17 exceptions
dhrubo kayal
 
Exception handling java
Exception handling javaException handling java
Exception handling java
Shashwat Shriparv
 
12 exception handling
12 exception handling12 exception handling
12 exception handling
Arriz San Juan
 
How to Study for Tests
How to Study for TestsHow to Study for Tests
How to Study for Tests
Michael Cohen
 
Erp
ErpErp
Apple i phone
Apple i phoneApple i phone
Apple i phone
Shashwat Shriparv
 
Cluster computing
Cluster computingCluster computing
Cluster computing
Shashwat Shriparv
 
Email
EmailEmail

Viewers also liked (8)

17 exceptions
17   exceptions17   exceptions
17 exceptions
 
Exception handling java
Exception handling javaException handling java
Exception handling java
 
12 exception handling
12 exception handling12 exception handling
12 exception handling
 
How to Study for Tests
How to Study for TestsHow to Study for Tests
How to Study for Tests
 
Erp
ErpErp
Erp
 
Apple i phone
Apple i phoneApple i phone
Apple i phone
 
Cluster computing
Cluster computingCluster computing
Cluster computing
 
Email
EmailEmail
Email
 

Similar to Javaexceptions

Java exception handling ppt
Java exception handling pptJava exception handling ppt
Java exception handling ppt
JavabynataraJ
 
Exception Handling.ppt
 Exception Handling.ppt Exception Handling.ppt
Exception Handling.ppt
Faisaliqbal203156
 
Exception handling in java
Exception handling  in javaException handling  in java
Exception handling in java
Elizabeth alexander
 
Exception handling
Exception handlingException handling
Exception handling
zindadili
 
Exception handling
Exception handlingException handling
Exception handling
Karthik Sekar
 
06 exceptions
06 exceptions06 exceptions
06 exceptions
Waheed Warraich
 
Java Exception Handling and examples about it
Java Exception Handling and examples about itJava Exception Handling and examples about it
Java Exception Handling and examples about it
2022002857mbit
 
Exception handling
Exception handlingException handling
Exception handling
Minal Maniar
 
exceptionvdffhhhccvvvv-handling-in-java.ppt
exceptionvdffhhhccvvvv-handling-in-java.pptexceptionvdffhhhccvvvv-handling-in-java.ppt
exceptionvdffhhhccvvvv-handling-in-java.ppt
yjrtytyuu
 
Exception hierarchy
Exception hierarchyException hierarchy
Exception hierarchy
Ashfaaq Mahroof
 
exception-handling-in-java.ppt unit 2
exception-handling-in-java.ppt unit 2exception-handling-in-java.ppt unit 2
exception-handling-in-java.ppt unit 2
thenmozhip8
 
Introduction to Exception
Introduction to ExceptionIntroduction to Exception
Introduction to Exception
Swabhav Techlabs
 
exception-handling-in-java.ppt
exception-handling-in-java.pptexception-handling-in-java.ppt
exception-handling-in-java.ppt
JAYESHRODGE
 
Z blue exception
Z blue   exceptionZ blue   exception
Z blue exception
Narayana Swamy
 
UNIT III 2021R.pptx
UNIT III 2021R.pptxUNIT III 2021R.pptx
UNIT III 2021R.pptx
RDeepa9
 
UNIT III 2021R.pptx
UNIT III 2021R.pptxUNIT III 2021R.pptx
UNIT III 2021R.pptx
RDeepa9
 
unit 4 msbte syallbus for sem 4 2024-2025
unit 4 msbte syallbus for sem 4 2024-2025unit 4 msbte syallbus for sem 4 2024-2025
unit 4 msbte syallbus for sem 4 2024-2025
AKSHAYBHABAD5
 
Ch-1_5.pdf this is java tutorials for all
Ch-1_5.pdf this is java tutorials for allCh-1_5.pdf this is java tutorials for all
Ch-1_5.pdf this is java tutorials for all
HayomeTakele
 
Best Practices in Exception Handling
Best Practices in Exception HandlingBest Practices in Exception Handling
Best Practices in Exception Handling
Lemi Orhan Ergin
 
Java: Exception
Java: ExceptionJava: Exception
Java: Exception
Tareq Hasan
 

Similar to Javaexceptions (20)

Java exception handling ppt
Java exception handling pptJava exception handling ppt
Java exception handling ppt
 
Exception Handling.ppt
 Exception Handling.ppt Exception Handling.ppt
Exception Handling.ppt
 
Exception handling in java
Exception handling  in javaException handling  in java
Exception handling in java
 
Exception handling
Exception handlingException handling
Exception handling
 
Exception handling
Exception handlingException handling
Exception handling
 
06 exceptions
06 exceptions06 exceptions
06 exceptions
 
Java Exception Handling and examples about it
Java Exception Handling and examples about itJava Exception Handling and examples about it
Java Exception Handling and examples about it
 
Exception handling
Exception handlingException handling
Exception handling
 
exceptionvdffhhhccvvvv-handling-in-java.ppt
exceptionvdffhhhccvvvv-handling-in-java.pptexceptionvdffhhhccvvvv-handling-in-java.ppt
exceptionvdffhhhccvvvv-handling-in-java.ppt
 
Exception hierarchy
Exception hierarchyException hierarchy
Exception hierarchy
 
exception-handling-in-java.ppt unit 2
exception-handling-in-java.ppt unit 2exception-handling-in-java.ppt unit 2
exception-handling-in-java.ppt unit 2
 
Introduction to Exception
Introduction to ExceptionIntroduction to Exception
Introduction to Exception
 
exception-handling-in-java.ppt
exception-handling-in-java.pptexception-handling-in-java.ppt
exception-handling-in-java.ppt
 
Z blue exception
Z blue   exceptionZ blue   exception
Z blue exception
 
UNIT III 2021R.pptx
UNIT III 2021R.pptxUNIT III 2021R.pptx
UNIT III 2021R.pptx
 
UNIT III 2021R.pptx
UNIT III 2021R.pptxUNIT III 2021R.pptx
UNIT III 2021R.pptx
 
unit 4 msbte syallbus for sem 4 2024-2025
unit 4 msbte syallbus for sem 4 2024-2025unit 4 msbte syallbus for sem 4 2024-2025
unit 4 msbte syallbus for sem 4 2024-2025
 
Ch-1_5.pdf this is java tutorials for all
Ch-1_5.pdf this is java tutorials for allCh-1_5.pdf this is java tutorials for all
Ch-1_5.pdf this is java tutorials for all
 
Best Practices in Exception Handling
Best Practices in Exception HandlingBest Practices in Exception Handling
Best Practices in Exception Handling
 
Java: Exception
Java: ExceptionJava: Exception
Java: Exception
 

Recently uploaded

Presentation of the OECD Artificial Intelligence Review of Germany
Presentation of the OECD Artificial Intelligence Review of GermanyPresentation of the OECD Artificial Intelligence Review of Germany
Presentation of the OECD Artificial Intelligence Review of Germany
innovationoecd
 
Main news related to the CCS TSI 2023 (2023/1695)
Main news related to the CCS TSI 2023 (2023/1695)Main news related to the CCS TSI 2023 (2023/1695)
Main news related to the CCS TSI 2023 (2023/1695)
Jakub Marek
 
“Building and Scaling AI Applications with the Nx AI Manager,” a Presentation...
“Building and Scaling AI Applications with the Nx AI Manager,” a Presentation...“Building and Scaling AI Applications with the Nx AI Manager,” a Presentation...
“Building and Scaling AI Applications with the Nx AI Manager,” a Presentation...
Edge AI and Vision Alliance
 
Building Production Ready Search Pipelines with Spark and Milvus
Building Production Ready Search Pipelines with Spark and MilvusBuilding Production Ready Search Pipelines with Spark and Milvus
Building Production Ready Search Pipelines with Spark and Milvus
Zilliz
 
Generating privacy-protected synthetic data using Secludy and Milvus
Generating privacy-protected synthetic data using Secludy and MilvusGenerating privacy-protected synthetic data using Secludy and Milvus
Generating privacy-protected synthetic data using Secludy and Milvus
Zilliz
 
National Security Agency - NSA mobile device best practices
National Security Agency - NSA mobile device best practicesNational Security Agency - NSA mobile device best practices
National Security Agency - NSA mobile device best practices
Quotidiano Piemontese
 
UI5 Controls simplified - UI5con2024 presentation
UI5 Controls simplified - UI5con2024 presentationUI5 Controls simplified - UI5con2024 presentation
UI5 Controls simplified - UI5con2024 presentation
Wouter Lemaire
 
Ocean lotus Threat actors project by John Sitima 2024 (1).pptx
Ocean lotus Threat actors project by John Sitima 2024 (1).pptxOcean lotus Threat actors project by John Sitima 2024 (1).pptx
Ocean lotus Threat actors project by John Sitima 2024 (1).pptx
SitimaJohn
 
Monitoring and Managing Anomaly Detection on OpenShift.pdf
Monitoring and Managing Anomaly Detection on OpenShift.pdfMonitoring and Managing Anomaly Detection on OpenShift.pdf
Monitoring and Managing Anomaly Detection on OpenShift.pdf
Tosin Akinosho
 
Best 20 SEO Techniques To Improve Website Visibility In SERP
Best 20 SEO Techniques To Improve Website Visibility In SERPBest 20 SEO Techniques To Improve Website Visibility In SERP
Best 20 SEO Techniques To Improve Website Visibility In SERP
Pixlogix Infotech
 
Energy Efficient Video Encoding for Cloud and Edge Computing Instances
Energy Efficient Video Encoding for Cloud and Edge Computing InstancesEnergy Efficient Video Encoding for Cloud and Edge Computing Instances
Energy Efficient Video Encoding for Cloud and Edge Computing Instances
Alpen-Adria-Universität
 
Your One-Stop Shop for Python Success: Top 10 US Python Development Providers
Your One-Stop Shop for Python Success: Top 10 US Python Development ProvidersYour One-Stop Shop for Python Success: Top 10 US Python Development Providers
Your One-Stop Shop for Python Success: Top 10 US Python Development Providers
akankshawande
 
Fueling AI with Great Data with Airbyte Webinar
Fueling AI with Great Data with Airbyte WebinarFueling AI with Great Data with Airbyte Webinar
Fueling AI with Great Data with Airbyte Webinar
Zilliz
 
Artificial Intelligence for XMLDevelopment
Artificial Intelligence for XMLDevelopmentArtificial Intelligence for XMLDevelopment
Artificial Intelligence for XMLDevelopment
Octavian Nadolu
 
GenAI Pilot Implementation in the organizations
GenAI Pilot Implementation in the organizationsGenAI Pilot Implementation in the organizations
GenAI Pilot Implementation in the organizations
kumardaparthi1024
 
Serial Arm Control in Real Time Presentation
Serial Arm Control in Real Time PresentationSerial Arm Control in Real Time Presentation
Serial Arm Control in Real Time Presentation
tolgahangng
 
Taking AI to the Next Level in Manufacturing.pdf
Taking AI to the Next Level in Manufacturing.pdfTaking AI to the Next Level in Manufacturing.pdf
Taking AI to the Next Level in Manufacturing.pdf
ssuserfac0301
 
Introduction of Cybersecurity with OSS at Code Europe 2024
Introduction of Cybersecurity with OSS  at Code Europe 2024Introduction of Cybersecurity with OSS  at Code Europe 2024
Introduction of Cybersecurity with OSS at Code Europe 2024
Hiroshi SHIBATA
 
Cosa hanno in comune un mattoncino Lego e la backdoor XZ?
Cosa hanno in comune un mattoncino Lego e la backdoor XZ?Cosa hanno in comune un mattoncino Lego e la backdoor XZ?
Cosa hanno in comune un mattoncino Lego e la backdoor XZ?
Speck&Tech
 
Skybuffer SAM4U tool for SAP license adoption
Skybuffer SAM4U tool for SAP license adoptionSkybuffer SAM4U tool for SAP license adoption
Skybuffer SAM4U tool for SAP license adoption
Tatiana Kojar
 

Recently uploaded (20)

Presentation of the OECD Artificial Intelligence Review of Germany
Presentation of the OECD Artificial Intelligence Review of GermanyPresentation of the OECD Artificial Intelligence Review of Germany
Presentation of the OECD Artificial Intelligence Review of Germany
 
Main news related to the CCS TSI 2023 (2023/1695)
Main news related to the CCS TSI 2023 (2023/1695)Main news related to the CCS TSI 2023 (2023/1695)
Main news related to the CCS TSI 2023 (2023/1695)
 
“Building and Scaling AI Applications with the Nx AI Manager,” a Presentation...
“Building and Scaling AI Applications with the Nx AI Manager,” a Presentation...“Building and Scaling AI Applications with the Nx AI Manager,” a Presentation...
“Building and Scaling AI Applications with the Nx AI Manager,” a Presentation...
 
Building Production Ready Search Pipelines with Spark and Milvus
Building Production Ready Search Pipelines with Spark and MilvusBuilding Production Ready Search Pipelines with Spark and Milvus
Building Production Ready Search Pipelines with Spark and Milvus
 
Generating privacy-protected synthetic data using Secludy and Milvus
Generating privacy-protected synthetic data using Secludy and MilvusGenerating privacy-protected synthetic data using Secludy and Milvus
Generating privacy-protected synthetic data using Secludy and Milvus
 
National Security Agency - NSA mobile device best practices
National Security Agency - NSA mobile device best practicesNational Security Agency - NSA mobile device best practices
National Security Agency - NSA mobile device best practices
 
UI5 Controls simplified - UI5con2024 presentation
UI5 Controls simplified - UI5con2024 presentationUI5 Controls simplified - UI5con2024 presentation
UI5 Controls simplified - UI5con2024 presentation
 
Ocean lotus Threat actors project by John Sitima 2024 (1).pptx
Ocean lotus Threat actors project by John Sitima 2024 (1).pptxOcean lotus Threat actors project by John Sitima 2024 (1).pptx
Ocean lotus Threat actors project by John Sitima 2024 (1).pptx
 
Monitoring and Managing Anomaly Detection on OpenShift.pdf
Monitoring and Managing Anomaly Detection on OpenShift.pdfMonitoring and Managing Anomaly Detection on OpenShift.pdf
Monitoring and Managing Anomaly Detection on OpenShift.pdf
 
Best 20 SEO Techniques To Improve Website Visibility In SERP
Best 20 SEO Techniques To Improve Website Visibility In SERPBest 20 SEO Techniques To Improve Website Visibility In SERP
Best 20 SEO Techniques To Improve Website Visibility In SERP
 
Energy Efficient Video Encoding for Cloud and Edge Computing Instances
Energy Efficient Video Encoding for Cloud and Edge Computing InstancesEnergy Efficient Video Encoding for Cloud and Edge Computing Instances
Energy Efficient Video Encoding for Cloud and Edge Computing Instances
 
Your One-Stop Shop for Python Success: Top 10 US Python Development Providers
Your One-Stop Shop for Python Success: Top 10 US Python Development ProvidersYour One-Stop Shop for Python Success: Top 10 US Python Development Providers
Your One-Stop Shop for Python Success: Top 10 US Python Development Providers
 
Fueling AI with Great Data with Airbyte Webinar
Fueling AI with Great Data with Airbyte WebinarFueling AI with Great Data with Airbyte Webinar
Fueling AI with Great Data with Airbyte Webinar
 
Artificial Intelligence for XMLDevelopment
Artificial Intelligence for XMLDevelopmentArtificial Intelligence for XMLDevelopment
Artificial Intelligence for XMLDevelopment
 
GenAI Pilot Implementation in the organizations
GenAI Pilot Implementation in the organizationsGenAI Pilot Implementation in the organizations
GenAI Pilot Implementation in the organizations
 
Serial Arm Control in Real Time Presentation
Serial Arm Control in Real Time PresentationSerial Arm Control in Real Time Presentation
Serial Arm Control in Real Time Presentation
 
Taking AI to the Next Level in Manufacturing.pdf
Taking AI to the Next Level in Manufacturing.pdfTaking AI to the Next Level in Manufacturing.pdf
Taking AI to the Next Level in Manufacturing.pdf
 
Introduction of Cybersecurity with OSS at Code Europe 2024
Introduction of Cybersecurity with OSS  at Code Europe 2024Introduction of Cybersecurity with OSS  at Code Europe 2024
Introduction of Cybersecurity with OSS at Code Europe 2024
 
Cosa hanno in comune un mattoncino Lego e la backdoor XZ?
Cosa hanno in comune un mattoncino Lego e la backdoor XZ?Cosa hanno in comune un mattoncino Lego e la backdoor XZ?
Cosa hanno in comune un mattoncino Lego e la backdoor XZ?
 
Skybuffer SAM4U tool for SAP license adoption
Skybuffer SAM4U tool for SAP license adoptionSkybuffer SAM4U tool for SAP license adoption
Skybuffer SAM4U tool for SAP license adoption
 

Javaexceptions

  • 1. Java Exception Handling 1
  • 2. Topics ● What is an Exception? ● What happens when an Exception occurs? ● Benefits of Exception Handling framework ● Catching exceptions with try-catch ● Catching exceptions with finally ● Throwing exceptions ● Rules in exception handling ● Exception class hierarchy ● Checked exception and unchecked exception ● Creating your own exception class ● Assertions 2
  • 4. What is an Exception? ● Exceptional event ● Error that occurs during runtime ● Cause normal program flow to be disrupted ● Examples – Divide by zero errors – Accessing the elements of an array beyond its range – Invalid input – Hard disk crash – Opening a non-existent file – Heap memory exhausted 4
  • 5. Exception Example 1 class DivByZero { 2 public static void main(String args[]) { 3 System.out.println(3/0); 4 System.out.println(“Pls. print me.”); 5 } 6 } 5
  • 6. Example: Default Exception Handling ● Displays this error message Exception in thread "main" java.lang.ArithmeticException: / by zero at DivByZero.main(DivByZero.java:3) ● Default exception handler – Provided by Java runtime – Prints out exception description – Prints the stack trace ● Hierarchy of methods where the exception occurred – Causes the program to terminate 6
  • 7. What Happens When an Exception Occurs? 7
  • 8. What Happens When an Exception Occurs? ● When an exception occurs within a method, the method creates an exception object and hands it off to the runtime system – Creating an exception object and handing it to the runtime system is called “throwing an exception” – Exception object contains information about the error, including its type and the state of the program when the error occurred 8
  • 9. What Happens When an Exception Occurs? ● The runtime system searches the call stack for a method that contains an exception handler 9
  • 10. What Happens When an Exception Occurs? ● When an appropriate handler is found, the runtime system passes the exception to the handler – An exception handler is considered appropriate if the type of the exception object thrown matches the type that can be handled by the handler – The exception handler chosen is said to catch the exception. ● If the runtime system exhaustively searches all the methods on the call stack without finding an appropriate exception handler, the runtime system (and, consequently, the program) terminates and uses the default exception handler 10
  • 11. Searching the Call Stack for an Exception Handler 11
  • 13. Benefits of Java Exception Handling Framework ● Separating Error-Handling code from “regular” business logic code ● Propagating errors up the call stack ● Grouping and differentiating error types 13
  • 14. Separating Error Handling Code from Regular Code ● In traditional programming, error detection, reporting, and handling often lead to confusing spaghetti code ● Consider pseudocode method here that reads an entire file into memory readFile { open the file; determine its size; allocate that much memory; read the file into memory; close the file; } 14
  • 15. Traditional Programming: No separation of error handling code ● In traditional programming, To handle such cases, the readFile function must have more code to do error detection, reporting, and handling. errorCodeType readFile { initialize errorCode = 0; open the file; if (theFileIsOpen) { determine the length of the file; if (gotTheFileLength) { allocate that much memory; if (gotEnoughMemory) { read the file into memory; if (readFailed) { errorCode = -1; } } else { errorCode = -2; 15 }
  • 16. Traditional Programming: No separation of error handling code ● } else { errorCode = -3; } close the file; if (theFileDidntClose && errorCode == 0) { errorCode = -4; } else { errorCode = errorCode and -4; } } else { errorCode = -5; } return errorCode; } 16
  • 17. Separating Error Handling Code from Regular Code ● Exceptions enable you to write the main flow of your code and to deal with the exceptional cases elsewhere readFile { try { open the file; determine its size; allocate that much memory; read the file into memory; close the file; } catch (fileOpenFailed) { doSomething; } catch (sizeDeterminationFailed) { doSomething; } catch (memoryAllocationFailed) { doSomething; } catch (readFailed) { doSomething; } catch (fileCloseFailed) { doSomething; 17 } }
  • 18. Separating Error Handling Code from Regular Code ● Note that exceptions don't spare you the effort of doing the work of detecting, reporting, and handling errors, but they do help you organize the work more effectively. 18
  • 19. Propagating Errors Up the Call Stack ● Suppose that the readFile method is the fourth method in a series of nested method calls made by the main program: method1 calls method2, which calls method3, which finally calls readFile ● Suppose also that method1 is the only method interested in the errors that might occur within readFile. method1 { call method2; } method2 { call method3; } method3 { call readFile; } 19
  • 20. Traditional Way of Propagating Errors method1 { ● Traditional error- errorCodeType error; error = call method2; notification techniques if (error) force method2 and doErrorProcessing; else method3 to propagate } proceed; the error codes returned by readFile up the call errorCodeType method2 { errorCodeType error; stack until the error error = call method3; codes finally reach if (error) return error; method1—the only else method that is proceed; } interested in them. errorCodeType method3 { errorCodeType error; error = call readFile; if (error) return error; else 20 proceed;
  • 21. Using Java Exception Handling method1 { try { ● A method can duck any call method2; exceptions thrown } catch (exception e) { within it, thereby doErrorProcessing; allowing a method } farther up the call stack } to catch it. Hence, only the methods that care method2 throws exception { about errors have to call method3; worry about detecting } errors ● Any checked exceptions method3 throws exception { that can be thrown call readFile; within a method must } be specified in its throws clause. 21
  • 22. Grouping and Differentiating Error Types ● Because all exceptions thrown within a program are objects, the grouping or categorizing of exceptions is a natural outcome of the class hierarchy ● An example of a group of related exception classes in the Java platform are those defined in java.io — IOException and its descendants – IOException is the most general and represents any type of error that can occur when performing I/O – Its descendants represent more specific errors. For example, FileNotFoundException means that a file could not be located on disk. 22
  • 23. Grouping and Differentiating Error Types ● A method can write specific handlers that can handle a very specific exception ● The FileNotFoundException class has no descendants, so the following handler can handle only one type of exception. catch (FileNotFoundException e) { ... } 23
  • 24. Grouping and Differentiating Error Types ● A method can catch an exception based on its group or general type by specifying any of the exception's superclasses in the catch statement. For example, to catch all I/O exceptions, regardless of their specific type, an exception handler specifies an IOException argument. // Catch all I/O exceptions, including // FileNotFoundException, EOFException, and so on. catch (IOException e) { ... 24 }
  • 25. Catching Exceptions with try-catch 25
  • 26. Catching Exceptions: The try-catch Statements ● Syntax: try { <code to be monitored for exceptions> } catch (<ExceptionType1> <ObjName>) { <handler if ExceptionType1 occurs> } ... } catch (<ExceptionTypeN> <ObjName>) { <handler if ExceptionTypeN occurs> } 26
  • 27. Catching Exceptions: The try-catch Statements 1 class DivByZero { 2 public static void main(String args[]) { 3 try { 4 System.out.println(3/0); 5 System.out.println(“Please print me.”); 6 } catch (ArithmeticException exc) { 7 //Division by zero is an ArithmeticException 8 System.out.println(exc); 9 } 10 System.out.println(“After exception.”); 11 } 12 } 27
  • 28. Catching Exceptions: Multiple catch 1 class MultipleCatch { 2 public static void main(String args[]) { 3 try { 4 int den = Integer.parseInt(args[0]); 5 System.out.println(3/den); 6 } catch (ArithmeticException exc) { 7 System.out.println(“Divisor was 0.”); 8 } catch (ArrayIndexOutOfBoundsException exc2) { 9 System.out.println(“Missing argument.”); 10 } 11 System.out.println(“After exception.”); 12 } 13 } 28
  • 29. Catching Exceptions: Nested try's class NestedTryDemo { public static void main(String args[]){ try { int a = Integer.parseInt(args[0]); try { int b = Integer.parseInt(args[1]); System.out.println(a/b); } catch (ArithmeticException e) { System.out.println(“Div by zero error!"); } //continued... 29
  • 30. Catching Exceptions: Nested try's } catch (ArrayIndexOutOfBoundsException) { System.out.println(“Need 2 parameters!"); } } } 30
  • 31. Catching Exceptions: Nested try's with methods 1 class NestedTryDemo2 { 2 static void nestedTry(String args[]) { 3 try { 4 int a = Integer.parseInt(args[0]); 5 int b = Integer.parseInt(args[1]); 6 System.out.println(a/b); 7 } catch (ArithmeticException e) { 8 System.out.println("Div by zero error!"); 9 } 10 } 11 //continued... 31
  • 32. Catching Exceptions: Nested try's with methods 12 public static void main(String args[]){ 13 try { 14 nestedTry(args); 15 } catch (ArrayIndexOutOfBoundsException e) { 16 System.out.println("Need 2 parameters!"); 17 } 18 } 19 } 32
  • 33. Catching Exceptions with finally 33
  • 34. Catching Exceptions: The finally Keyword ● Syntax: try { <code to be monitored for exceptions> } catch (<ExceptionType1> <ObjName>) { <handler if ExceptionType1 occurs> } ... } finally { <code to be executed before the try block ends> } ● Contains the code for cleaning up after a try or a catch 34
  • 35. Catching Exceptions: The finally Keyword ● Block of code is always executed despite of different scenarios: – Forced exit occurs using a return, a continue or a break statement – Normal completion – Caught exception thrown ● Exception was thrown and caught in the method – Uncaught exception thrown ● Exception thrown was not specified in any catch block in the method 35
  • 36. Catching Exceptions: The finally Keyword 1 class FinallyDemo { 2 static void myMethod(int n) throws Exception{ 3 try { 4 switch(n) { 5 case 1: System.out.println("1st case"); 6 return; 7 case 3: System.out.println("3rd case"); 8 throw new RuntimeException("3!"); 9 case 4: System.out.println("4th case"); 10 throw new Exception("4!"); 11 case 2: System.out.println("2nd case"); 12 } 13 //continued... 36
  • 37. Catching Exceptions: The finally Keyword 14 } catch (RuntimeException e) { 15 System.out.print("RuntimeException: "); 16 System.out.println(e.getMessage()); 17 } finally { 18 System.out.println("try-block entered."); 19 } 20 } 21 //continued... 37
  • 38. Catching Exceptions: The finally Keyword 22 public static void main(String args[]){ 23 for (int i=1; i<=4; i++) { 24 try { 25 FinallyDemo.myMethod(i); 26 } catch (Exception e){ 27 System.out.print("Exception caught: "); 28 System.out.println(e.getMessage()); 29 } 30 System.out.println(); 31 } 32 } 33 } 38
  • 40. Throwing Exceptions: The throw Keyword ● Java allows you to throw exceptions (generate exceptions) throw <exception object>; ● An exception you throw is an object – You have to create an exception object in the same way you create any other object ● Example: throw new ArithmeticException(“testing...”); 40
  • 41. Example: Throwing Exceptions 1 class ThrowDemo { 2 public static void main(String args[]){ 3 String input = “invalid input”; 4 try { 5 if (input.equals(“invalid input”)) { 6 throw new RuntimeException("throw demo"); 7 } else { 8 System.out.println(input); 9 } 10 System.out.println("After throwing"); 11 } catch (RuntimeException e) { 12 System.out.println("Exception caught:" + e); 13 } 14 } 15 } 41
  • 42. Rules in Exception Handling 42
  • 43. Rules on Exceptions ● A method is required to either catch or list all exceptions it might throw – Except for Error or RuntimeException, or their subclasses ● If a method may cause an exception to occur but does not catch it, then it must say so using the throws keyword – Applies to checked exceptions only ● Syntax: <type> <methodName> (<parameterList>) throws <exceptionList> { <methodBody> 43 }
  • 44. Example: Method throwing an Exception 1 class ThrowingClass { 2 static void meth() throws ClassNotFoundException { 3 throw new ClassNotFoundException ("demo"); 4 } 5 } 6 class ThrowsDemo { 7 public static void main(String args[]) { 8 try { 9 ThrowingClass.meth(); 10 } catch (ClassNotFoundException e) { 11 System.out.println(e); 12 } 13 } 44 14 }
  • 45. Exception Class Hierarchy 45
  • 46. The Error and Exception Classes ● Throwable class – Root class of exception classes – Immediate subclasses ● Error ● Exception ● Exception class – Conditions that user programs can reasonably deal with – Usually the result of some flaws in the user program code – Examples ● Division by zero error ● Array out-of-bounds error 46
  • 47. The Error and Exception Classes ● Error class – Used by the Java run-time system to handle errors occurring in the run-time environment – Generally beyond the control of user programs – Examples ● Out of memory errors ● Hard disk crash 47
  • 48. Exception Classes and Hierarchy 48
  • 49. Exception Classes and Hierarchy ● Multiple catches should be ordered from subclass to superclass. 1 class MultipleCatchError { 2 public static void main(String args[]){ 3 try { 4 int a = Integer.parseInt(args [0]); 5 int b = Integer.parseInt(args [1]); 6 System.out.println(a/b); 7 } catch (Exception ex) { 8 } catch (ArrayIndexOutOfBoundsException e) { 9 } 10 } 11 } 49
  • 51. Checked and Unchecked Exceptions ● Checked exception – Java compiler checks if the program either catches or lists the occurring checked exception – If not, compiler error will occur ● Unchecked exceptions – Not subject to compile-time checking for exception handling – Built-in unchecked exception classes ● Error ● RuntimeException ● Their subclasses – Handling all these exceptions may make the program cluttered and may become a nuisance 51
  • 52. Creating Your Own Exception Class 52
  • 53. Creating Your Own Exception Class ● Steps to follow – Create a class that extends the RuntimeException or the Exception class – Customize the class ● Members and constructors may be added to the class ● Example: 1 class HateStringExp extends RuntimeException { 2 /* some code */ 3 } 53
  • 54. How To Use Your Own Exceptions 1 class TestHateString { 2 public static void main(String args[]) { 3 String input = "invalid input"; 4 try { 5 if (input.equals("invalid input")) { 6 throw new HateStringExp(); 7 } 8 System.out.println("Accept string."); 9 } catch (HateStringExp e) { 10 System.out.println("Hate string!”); 11 } 12 } 54 13 }
  • 56. What are Assertions? ● Allow the programmer to find out if an assumption was met – Example: month ● Extension of comments wherein the assert statement informs the person reading the code that a particular condition should always be satisfied – Running the program informs you if assertions made are true or not – If an assertion is not true, an AssertionError is thrown ● User has the option to turn it off or on at runtime 56
  • 57. Enabling or Disabling Assertions ● Program with assertions may not work properly if used by clients not aware that assertions were used in the code ● Compiling – With assertion feature: javac –source 1.4 MyProgram.java – Without the assertion feature: javac MyProgram.java ● Enabling assertions: – Use the –enableassertions or –ea switch. java –enableassertions MyProgram 57
  • 58. Assert Syntax ● Two forms: – Simpler form: assert <expression1>; where ● <expression1> is the condition asserted to be true – Other form: assert <expression1> : <expression2>; where ● <expression1> is the condition asserted to be true ● <expression2> is some information helpful in diagnosing why the statement failed 58
  • 59. Assert Syntax 1 class AgeAssert { 2 public static void main(String args[]) { 3 int age = Integer.parseInt(args[0]); 4 assert(age>0); 5 /* if age is valid (i.e., age>0) */ 6 if (age >= 18) { 7 System.out.println(“You're an adult! =)”); 8 } 9 } 10 } 59