Exceptions

Nicholas Duchon: Jun 14, 2019

Key Concepts:


Introduction

Exceptions? Here is a quick introduction to the key points. 


Catching div by 0:

public class DivZeroTest {
  public static void main (String [] args) {
    try {
      int k = 1, j = 0;
      System.out.println ("Div: " + k/j);
    } catch (ArithmeticException e) {
      System.out.println ("Exception: " + e);

      System.out.println ("\n***** e.getMessage ():");
      System.out.println ("Exception: " + e.getMessage());

      System.out.println ("\n***** Thread.dumpStack ():");
      Thread.dumpStack ();

      System.out.println ("\n***** e.printStackTrace ():");
      e.printStackTrace ();
    } // end try/catch
  } // end main
} // end class DivZeroTest

Output:

Exception: java.lang.ArithmeticException: / by zero

***** e.getMessage ():
Exception: / by zero

***** Thread.dumpStack ():
java.lang.Exception: Stack trace
    at java.lang.Thread.dumpStack(Thread.java:1329)
    at DivZeroTest.main(DivZeroTest.java:11)

***** e.printStackTrace ():
java.lang.ArithmeticException: / by zero
    at DivZeroTest.main(DivZeroTest.java:5)

GUI:

JOptionPane.showMessageDialog(frame, "Eggs are not supposed to be green.");

Unchecked Exception

public class Exceptions0b {
   static void methodA () {
      try {
         methodB();
      } catch (java.lang.RuntimeException e) {
         System.out.println (e.toString());
      } // end try/catch
  
} // end methodA
  
   static void methodB () {
      throw new java.lang.RuntimeException ("This one is not checked");
  
} // end methodB
  
   public static void main (String [] args) {
      methodA ();
  
} // end main
} // end class Excaptions 0b


Checked Exception

public class Exceptions0a {
   static void methodA () {
      try {
      methodB();
      } catch (java.lang.Exception e) {
         System.out.println (e.toString());
      } // end try/catch
   } // end methodA
  
   static void methodB () throws java.lang.Exception {
      throw new java.lang.Exception ("Have fun with this one");
  
} // end methodB
  
   public static void main (String [] args) {
      methodA ();
  
} // end main
} // end class Excaptions 0a


Finally

public class Exceptions0c {
   static void methodA () {
      try {
         methodB();
         System.out.println ("Everything was fine");
      } catch (java.lang.RuntimeException e) {
         System.out.println (e.toString());
      } finally {
         System.out.println ("Finally clause: even if the exception was thrown!");
      } // end try/catch
      System.out.println ("After the fox!");
  
} // end methodA
  
   static void methodB () throws java.lang.Exception {
      throw new java.lang.Exception ("Have fun with this one");
  
} // end methodB  


   public static void main (String [] args) {
      methodA ();
  
} // end main

}
// end class Excaptions 0c




ND.