0% found this document useful (0 votes)
1 views16 pages

Exception Handling

The document provides an overview of exception handling in programming, explaining the concepts of exceptions, errors, and the importance of handling them properly. It covers various methods for printing exception information, the use of try-catch blocks, the significance of finally blocks, and the throw and throws statements. Additionally, it discusses the differences between checked and unchecked exceptions and the proper structure for handling multiple exceptions.

Uploaded by

kushsevak9
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
1 views16 pages

Exception Handling

The document provides an overview of exception handling in programming, explaining the concepts of exceptions, errors, and the importance of handling them properly. It covers various methods for printing exception information, the use of try-catch blocks, the significance of finally blocks, and the throw and throws statements. Additionally, it discusses the differences between checked and unchecked exceptions and the proper structure for handling multiple exceptions.

Uploaded by

kushsevak9
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 16

1 /*

2
3 Exception: An unwanted unexpected event that disturb normal flow of the
program is called exception
4 --> It is highly recommended to handle exceptions.
5 --> The main objective of exception hanlding is normal
termination of the program.
6
7 Exception Handling:
8 --> Exception handling does not mean repairing an exception.
9 --> We have to define alternative way to conitune rest of the
program normally.
10 --> This way of "Defining alternative" is nothing but exception
handling.
11
12 --> Throwable acts as a root for exception hierarchy.
13 --> Throwable class contains the two child classes: Exception and Error
14
15 Exception: Most of the cases exceptions are caused by our program and
these are recoverable.
16 Error: Most of the cases errors are not caused by our programs these are
due to lack of system resources and these are not recoverable.
17
18 --> There are two types of Exceptions: Checked and Unchecked Exceptions
19
20 Note: Whether exeption is checked or unchecked compulsory it should
occur at runtime only.
21 --> There is no chance of occuring any exception at compile time.
22
23 Examples of Exceptions:
24 (1) RuntimeException
25 - ArithmeticException
26 - NullPointerException
27 - IndexOutOfBoundsException
28 - IllegalArgumentException
29 - ClassCastException
30 - IllegalStateException
31 (2) IOException
32 - EOFException
33 - FileNotFoundException
34 (3) SQLException
35 (4) ServletException
36 and Many more.........
37
38
39 Exception Handling by try catch:
40
41 --> It is highly recommended to handle exceptions.
42 --> In our program the code which may cause an exception is called
risky code we have to place risky code inside try block
43 --> and the corresponding handling code inside catch block.
44
45
46 Note:
47 1. Within the try block if anywhere an exception raised then rest of
try block won't be executed even though we handled that exception.
48 -> Hence we have to place only risky code inside try and length
of the try block should be as less as possible.
49
50 */
51
52 package ExceptionHandling;
53
54 public class EH1 {
55 public static void main(String[] args) {
56 System.out.println("Hello");
57 // Without try catch
58 System.out.println(5 / 0);
59
60 /*
61 * with try catch
62 *
63 * try{
64 * System.out.println(5 / 0);
65 * } catch (ArithmeticException e) {
66 * System.out.println(10 / 2);
67 * }
68 *
69 */
70
71 System.out.println("World");
72 }
73
74 }
75
1 /*
2
3 Various Methods to print Exception Information:
4
5 --> Throwable class defines the following methods to print exception
information to the console.
6
7 1. printStackTrace():
8 --> This method prints exception information in the following format:
9 Name of the exception: Description of the exception
10 Stack trace
11
12 2. toString():
13 --> This method prints exception information in the following format.
14 Name of the exception: Description of the exception
15
16 3. getMessage():
17 --> This method returns only description of the exception
18 Description
19
20 NOTE: Default exception handler internally uses printStackTrace() method
to print exception information to the console.
21
22 */
23
24 package ExceptionHandling;
25
26 public class EH2 {
27 public static void main(String[] args) {
28 int a[] = { 1, 2, 3, 4 };
29
30 try{
31 for (int i=1; i<=4;i++){
32 System.out.println(a[i]);
33 }
34 } catch (ArrayIndexOutOfBoundsException e) {
35 System.out.println("Output of printStackTrace Method: ");
36 e.printStackTrace();
37
38 System.out.println("Output of toString Method: ");
39 // System.out.println(e.toString());
40 System.out.println(e);
41
42 System.out.println("Output of getMessage Method: ");
43 System.out.println(e.getMessage());
44
45 }
46 }
47 }
48
1 /*
2
3 try with multiple catch blocks:
4
5 --> The way of handling an exception is varied from exception to
exception
6 hence for every exception raise a separate catch block that is try
with multiple catch blocks is possible and
7 recommended to use.
8
9 */
10 package ExceptionHandling;
11
12 public class EH3 {
13 public static void main(String[] args) {
14 try {
15
16 //int c = 5 / 0;
17
18 int a[] = { 1, 2, 3, 4 };
19 for (int i = 1; i <= 4; i++) {
20 System.out.println(a[i]);
21 }
22 // int c = 5 / 0;
23
24 } catch (ArithmeticException e) {
25 System.out.println(e);
26 } catch (ArrayIndexOutOfBoundsException e) {
27 System.out.println(e);
28 }
29 System.out.println("Last statement Executed");
30 }
31 }
32
1 /*
2
3 try with multiple catch blocks:
4
5 --> If try with multiple catch blocks presents then order of catch
blocks is very important.
6 --> It should be from child to parent.
7 --> By mistake if we are taking from parent to child then we will get
compile time error (C.E.) saying
8 "exception xxxx has already been caught".
9
10 */
11
12 package ExceptionHandling;
13
14 public class EH4 {
15 public static void main(String[] args) {
16 try {
17
18 // int c = 5 / 0;
19
20 int a[] = { 1, 2, 3, 4 };
21 for (int i = 1; i <= 4; i++) {
22 System.out.println(a[i]);
23 }
24 // int c = 5 / 0;
25
26 } catch (Exception e) {
27 System.out.println(e);
28 }
29 // catch (ArrayIndexOutOfBoundsException e) { // Here we used
child after parent so, C.E: Unreachable catch block
30 // // for
ArrayIndexOutOfBoundsException. It is already handled by the
31 // // catch block for
Exception
32 // System.out.println(e);
33 // }
34 System.out.println("Last statement Executed");
35 }
36 }
37
1 /*
2
3 Finally Block:
4
5 --> It is never recommended to take clean up code inside try block
because there is
6 no guarantee for the execution of every statement inside a try
block.
7 --> It is never recommended to place clean up code inside catch
block because
8 if there is no exception then catch block won't be executed.
9 --> We require some place to maintain clean up code which should be
executed always
10 irrespective of whether execution raised or not raised and
whether handled or not
11 handled such type of place is nothing but "finally block".
12 --> Hence, Main objective of finally block is to maintain cleaup
code.
13
14 Syntax:
15
16 try{
17 // risky code
18 } catch (X e){
19 // handling code
20 } finally {
21 // cleanup code
22 }
23 */
24
25 package ExceptionHandling;
26
27 public class EH5 {
28 public static void main(String[] args) {
29
30 try {
31 System.out.println("Try block executed");
32 //System.out.println(10/0);
33 } catch (ArithmeticException e) {
34 System.out.println("Catch block executed");
35 System.out.println(e);
36 } finally {
37 System.out.println("Finally block executed");
38 }
39
40 }
41 }
42
1 /*
2
3 Finally Block:
4
5 --> Even though return present in try or catch blocks, first finally
will be executed.
6 --> And after that only return statement will be considered.
7 --> "finally" dominates "return statement".
8
9 */
10
11 package ExceptionHandling;
12
13 public class EH6 {
14 public static void main(String[] args) {
15 try{
16 System.out.println("try block executed");
17 return;
18 } catch (ArithmeticException e) {
19 System.out.println("catch block executed");
20 } finally {
21 System.out.println("finally block executed");
22 }
23
24 }
25 }
26
1 /*
2
3 Finally Block:
4
5 --> If return statment is present in try, catch and finally block
then finally block return statement will be considered.
6 --> There is only one situation where the finally block won't be
executed, i.e., whenever we are using System.exit(0) method.
7
8 */
9
10 package ExceptionHandling;
11
12 public class EH7 {
13 public static void main(String[] args) {
14 System.out.println(m1());
15 }
16
17 public static int m1() {
18 try{
19 System.out.println(5/0);
20 return 111;
21 } catch (ArithmeticException e) {
22 return 222;
23 } finally {
24 System.out.println("finally executed");
25 return 333;
26 }
27 }
28 }
29
1 /*
2
3 throw Statement:
4
5 --> To create exception object explicitly, one can use throw
statement.
6 --> By using throw statement, we can hand over exception to the JVM
manually.
7 --> The result of following 2 examples will be exactly the same.
8
9 */
10
11 package ExceptionHandling;
12
13 /*
14 In this case creation of ArithmeticException object and handover to
the JVM will be performed
15 automatically by the main() method.
16
17 */
18
19 public class EH8 {
20 public static void main(String[] args) {
21 System.out.println(5 / 0);
22 }
23 }
24
25 /*
26 In this case we are creating exception object explicitly and
handover to the JVM manually.
27 */
28
29 class EH8_1 {
30 public static void main(String[] args) {
31 throw new ArithmeticException("/ by Zero by CVM");
32 }
33 }
34
35 /*
36 CASE 1:
37 If Exception object refers null then we will get
NullPointerException.
38 */
39
40 class EH8_2_C1 {
41
42 static ArithmeticException e = new ArithmeticException(); // R.E:
ArithmeticException
43
44 public static void main(String[] args) {
45 throw e;
46 }
47 }
48
49 class EH8_3_C1 {
50
51 static ArithmeticException e; // R.E.: NullPointerException
52
53 public static void main(String[] args) {
54 throw e;
55 }
56 }
57
58 /*
59 CASE 2:
60 After throw statement we can't take any statement directly
otherwise we will get C.E. saying
61 "Unreachable code"
62 */
63
64
65 class EH8_4_C2 {
66 public static void main(String[] args) {
67 System.out.println(5 / 0); // R.E. ArithmeticException
68 System.out.println("Statement 1");
69 }
70 }
71
72 class EH8_5_C2 {
73 public static void main(String[] args) {
74 throw new ArithmeticException("/ by zero by CVM");
75 // System.out.println("Statement 1"); // C.E. Unreachable code
76 }
77 }
78
79 /*
80 CASE 3:
81 We can use throw keyword only for Throwable types otherwise we
will get C.E. saying
82 "incompatible types"
83 */
84
85 class EH8_6_C3 {
86 public static void main(String[] args) {
87 // throw new EH8_6_C3(); // C.E.
88 // Exception in thread "main" java.lang.Error: Unresolved
compilation problem:
89 // No exception of type EH8_6_C3 can be thrown; an exception
type must be a subclass of Throwable
90 }
91 }
92
93 class EH8_7_C3 extends RuntimeException {
94 public static void main(String[] args) {
95 throw new EH8_7_C3(); // R.E.: Exception in thread "main"
ExceptionHandling.EH8_7_C3
96 // at
ExceptionHandling.EH8_7_C3.main(EH8.java:96
)
97 }
98 }
99
100 class EH8_8_C3 extends Throwable {
101 public static void main(String[] args) {
102 // throw new EH8_8_C3(); // C.E.: Unhandled Exception type
EH8_8_C3
103 }
104 }
105
106 class EH8_9_C3 extends Exception {
107 public static void main(String[] args) {
108 // throw new EH8_9_C3(); // C.E.: Unhandled Exception type
EH8_9_C3
109 }
110 }
1 /*
2 throws Statement:
3 --> In program if there is chance of raising checked exception
then, compulsory we should handle it,
4 --> Either by try.... catch or by throws keyword,
5 --> Otherwise we will get C.E.
6
7
8 */
9
10 package ExceptionHandling;
11
12
13 public class EH9 {
14 public static void main(String[] args) {
15 // Thread.sleep(3000); // C.E.: Unhandled exception type
InterruptedException
16 }
17 }
18
19 /*
20 We can handle above C.E. by using following 2 ways.
21 1. try...catch
22 2. throws keyword
23 */
24
25 class EH9_1 {
26 public static void main(String[] args) {
27 try {
28 Thread.sleep(3000);
29 System.out.println("Statement 1");
30 } catch (InterruptedException e) {
31 System.out.println(e);
32 }
33 }
34 }
35
36 class EH9_2 {
37 public static void main(String[] args) throws InterruptedException {
38 Thread.sleep(3000);
39 System.out.println("Statement 1");
40 }
41 }
42
43 /*
44
45 1. Main objective of "throws keyword" is to delicate the responsibility
of exception handling to the caller method.
46 2. "throws" keyword required only for checked exceptions.
47 3. "throws" keyword required only to convience compiler.
48 4. Usage of "throws" keyword does not prevent abrnormal termination of
the program.
49 5. We can not use "throws keyword with classes and interfaces"
50
51 */
52
53 class EH9_3 {
54 public static void main(String[] args) throws InterruptedException {
55 m1();
56 }
57
58 static void m1() throws InterruptedException {
59 m2();
60 }
61
62 static void m2() throws InterruptedException {
63 m3();
64 }
65
66 static void m3() throws InterruptedException {
67 Thread.sleep(3000);
68 System.out.println("Statement 1");
69 }
70 }
71
72 // In above program, if we are removing at least one throws keyword then
the program will give C.E.
73
74 /*
75 CASE 1:
76 We can use throws keyword only for Throwable types otherwise we
will get compile time error
77 */
78
79 class EH9_4_C1{
80 public static void main(String[] args) /* throws EH9_4_C1 */ {
81 // C.E.: No exception of type EH9_4_C1 can be thrown; an
exception type must be
82 // a subclass of Throwable
83 }
84 }
85
86 class EH9_5_C1 extends Throwable /*(Exception, RuntimeException also
possible)*/ {
87 public static void main(String[] args) throws EH9_5_C1 {
88
89 }
90 }
91
92 /*
93 CASE 2:
94 */
95
96 class EH9_6_C2 {
97 public static void main(String[] args) /* throws Exception */ {
98 // throw new Exception(); // C.E.: Because Exception is
partially checked class, hence requires Handling
99 // throw new Throwable(); // C.E.: Because Throwable is
partially checked class, hence requires Handling
100
101 // Solution is main method throws Exception.
102 }
103 }
104
105 class EH9_7_C2 {
106 public static void main(String[] args) {
107 throw new Error(); // R.E.
108 }
109 }
110
111 /*
112 CASE 3:
113 In our program, if there is no chance of rising an exception
then we can' right catch block for that exception
114 otherwise we will get C.E. saying exception xxxx is never thrown
in body of corresponding try statement.
115 --> This rule is applicable only for "fully checked exception".
116 */
117
118 class EH9_8_C3 {
119 public static void main(String[] args) {
120 try{
121 System.out.println("Statement 1");
122 }catch(Exception e){ // Exception is partially checked
123 System.out.println(e);
124 }
125 }
126 }
127
128 class EH9_9_C3 {
129 public static void main(String[] args) {
130 try {
131 System.out.println("Statement 1");
132 } catch (ArithmeticException e) { // ArithmeticException is
unchecked exception
133 System.out.println(e);
134 }
135 }
136 }
137
138 class EH9_10_C3 {
139 public static void main(String[] args) {
140 // try {
141 // System.out.println("Statement 1");
142 // } catch (java.io.IOException e) { // C.E.:
143 // System.out.println(e);
144 // }
145 }
146 }
147 // IOException is fully checked, Hence C.E.
148 // Unreachable catch block for IOException. This exception is never
thrown from the try statement body
149
150 class EH9_11_C3 {
151 public static void main(String[] args) {
152 // try {
153 // System.out.println("Statement 1");
154 // } catch (InterruptedException e) { // C.E.
155 // System.out.println(e);
156 // }
157 }
158 }
159
160
161 // InterruptedException is fully checked, Hence C.E.
162 // Unreachable catch block for InterruptedException. This exception is
never thrown from the try statement body
163
164 class EH9_12_C3 {
165 public static void main(String[] args) {
166 try {
167 System.out.println("Statement 1");
168 } catch (Error e) { // Error is unchecked.
169 System.out.println(e);
170 }
171 }
172 }
1 /*
2 Customized Exceptions (User defined Exceptions):
3
4 --> We can create our own exception to meet our programming
requirements.
5 --> Such type of exceptions are called customized exceptions.
6
7 Note: It is highly recommended to maintain our customized exceptions as
unchecked by extending RuntimeException.
8 --> We can catch any Throwable type including Errors also.
9
10 */
11
12 class TooYoungException extends RuntimeException {
13 TooYoungException(String s) {
14 super(s);
15 }
16 }
17
18 class TooOldException extends RuntimeException {
19 TooOldException(String s) {
20 super(s);
21 }
22 }
23
24 class MarriageB {
25 public static void main(String[] args) {
26 int age = 0;
27 try{
28 age = Integer.parseInt(args[0]);
29 if (age > 60) {
30 throw new TooYoungException("Please wait some more
time......You will get best match");
31 } else if (age < 18) {
32 throw new TooOldException("Your age already crossed...No
chance of getting Married");
33 } else {
34 System.out.println("You will get match details soon by
mail");
35 }
36 }
37 catch (ArrayIndexOutOfBoundsException e) {
38 System.out.println(e);
39 }
40 }
41 }

You might also like