|
| 1 | +package exceptions; |
| 2 | + |
| 3 | +import java.io.FileNotFoundException; |
| 4 | +import java.io.FileReader; |
| 5 | +import java.io.IOException; |
| 6 | + |
| 7 | +class Student { |
| 8 | + int id; |
| 9 | + |
| 10 | + void setId (int id) { |
| 11 | + this.id = id; |
| 12 | + } |
| 13 | +} |
| 14 | + |
| 15 | +public class LearnStackTrace { |
| 16 | + public static void main(String[] args) throws IOException { |
| 17 | + try { |
| 18 | + level1(); |
| 19 | + } catch (Exception o) { |
| 20 | +// StackTraceElement stackTrace[] = o.getStackTrace(); |
| 21 | +// for(StackTraceElement st: stackTrace) { |
| 22 | +// System.out.println(st); |
| 23 | +// } |
| 24 | + |
| 25 | + o.printStackTrace(); |
| 26 | + } |
| 27 | + |
| 28 | + // null-pointer exception |
| 29 | + // unchecked exception -> these exceptions are not checked at compile time |
| 30 | + Student a = null; |
| 31 | + a.setId(123); |
| 32 | + |
| 33 | + |
| 34 | + method2(); |
| 35 | + System.out.println("Hello"); |
| 36 | + } |
| 37 | + |
| 38 | + public static void method2() throws FileNotFoundException { |
| 39 | + method1(); |
| 40 | + } |
| 41 | + |
| 42 | + public static void method1() throws FileNotFoundException { |
| 43 | + // checked exception -> checked at compile time |
| 44 | + // either handle this using try catch |
| 45 | + // or make it's caller responsible, write "throws Exception" in method in which its present |
| 46 | + // FileReader fileReader = new FileReader("a.txt"); |
| 47 | + |
| 48 | + try { |
| 49 | + FileReader fileReader = new FileReader("a.txt"); |
| 50 | + } catch (FileNotFoundException e) { |
| 51 | + System.out.println("File not found"); |
| 52 | + throw new FileNotFoundException("oops!"); |
| 53 | + } |
| 54 | + } |
| 55 | + |
| 56 | + // not needed to do that throws etc. here since its unchecked exception |
| 57 | + public static void someMethod() { |
| 58 | + throw new ArithmeticException(); |
| 59 | + } |
| 60 | + |
| 61 | + public static void level3() { |
| 62 | + int[] array = new int[5]; |
| 63 | + array[5] = 10; |
| 64 | + } |
| 65 | + |
| 66 | + public static void level2() { |
| 67 | + level3(); |
| 68 | + } |
| 69 | + |
| 70 | + public static void level1() { |
| 71 | + level2(); |
| 72 | + } |
| 73 | + |
| 74 | + public static int divide (int a, int b) { |
| 75 | + try { |
| 76 | + return a/b; |
| 77 | + } catch (Exception e) { |
| 78 | + return -1; |
| 79 | + } |
| 80 | + finally { |
| 81 | + // this will execute, no matter try or catch which is executing |
| 82 | + // we can print even when return statements are there in try/catch |
| 83 | + System.out.println("Bye"); |
| 84 | + } |
| 85 | +// System.out.println("Bye"); |
| 86 | + } |
| 87 | +} |
0 commit comments