Advertisement
yo2man

Tutorial 36 (Runtime vs Checked Exceptions)

May 19th, 2015
256
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 5 1.12 KB | None | 0 0
  1. //Tutorial 36 (Runtime vs Checked Exceptions) //easy
  2.  
  3. //Two basic types of exceptions in Java:
  4.     //1.Checked Exceptions: (what we have looked at so far in the previous two tutorials)
  5.             //-it forces you to handle it
  6.  
  7.     //2.Runtime Exceptions
  8.             //-exceptions that you are not forced to handle. also called Unchecked Exceptions. such as division by zero
  9.        
  10. public class App {
  11.  
  12.     public static void main(String[] args) {
  13.         // Arithmetic exception ... (divide by zero)
  14.         int value = 7;
  15.        
  16.         value = value/0; //this compiles but it still throws an exception: "Exception in thread "main" java.lang.ArithmeticException: / by zero"
  17.         //^this is a Runtime Exception
  18.        
  19.         String text = null;
  20.        
  21.         System.out.println(text.length());
  22.  
  23.         // You can actually handle RuntimeExceptions if you want to;
  24.         // for example, here we handle an ArrayIndexOutOfBoundsException
  25.         String[] texts = { "one", "two", "three" };
  26.  
  27.         try {
  28.             System.out.println(texts[3]);
  29.         } catch (ArrayIndexOutOfBoundsException e) {
  30.             System.out.println(e.toString());
  31.         }
  32.     }
  33.  
  34. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement