5-Exception Handling - 1.2 (Creating Own Exception), Java Programming - Arrays and Linked List-29-05
5-Exception Handling - 1.2 (Creating Own Exception), Java Programming - Arrays and Linked List-29-05
What is Exception?
Exception Handling
An exception can occur for following
reasons.
•User error
•Programmer error
•Physical error
1 import java.util.*;
2 public class MyClass
3 {
4 public static void main(String args[])
5 {
6 int x=10;
7 int y=0;
8 int z=x/y;
9 System.out.println(z);
10 }
11 }
12
13
14
15
Output
Exception in thread "main" java.lang.ArithmeticException: / by zero at
MyClass.main(MyClass.java:6)
1 import java.io.*;
2 public class Main {
3 public static void main(String[] args){
4 System.out.println("First line");
5 System.out.println("Second line");
6 int[] myIntArray = new int[]{1, 2, 3};
7 print(myIntArray);
8 System.out.println("Third line");
9 }
10 public static void print(int[] arr) {
11 System.out.println(arr[3]);
12 System.out.println("Fourth element successfully displayed!");
13 }
14 }
15
Output
First line
Second line
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 3
at Main.print(Main.java:11)
at Main.main(Main.java:7)
Hierarchy of Java Exception classes
Exception IOException
SQLException
Throwable ClassNot
FoundException
RuntimeException
Error
Types of Exception
•Checked Exception
•Unchecked Exception
1 //Example for Checked exception
2 import java.io.FileInputStream;
3 public class Main {
4 public static void main(String[] args) {
5 FileInputStream fis = null;
6 fis = new FileInputStream(“D:/myfile.txt");
7 int k;
8 while(( k = fis.read() ) != -1)
9 {
10 System.out.print((char)k);
11 }
12 fis.close();
13 }
14 }
15
Output
Exception in thread "main" java.lang.Error: Unresolved compilation
problems:
Unhandled exception type FileNotFoundException
Unhandled exception type IOException
Unhandled exception type IOException
1 //Example for Unchecked exception
2 import java.io.*;
3 public class Main {
4 public static void main(String[] args){
5 int[] arr = new int[]{7, 11, 30, 63};
6 System.out.println(arr[5]);
7 }
8 }
9
10
11
12
13
14
15
Output
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 5
at Main.main(Main.java:5)
Exception Handling
Exception Handling?
First line
Second line
The array doesn't have fourth element!
Third line
Internal Working of try-catch Block
System.out.print(arr[3]) Exception object
An object of
exception class is
thrown
Is
Handled?
no yes
JVM
• Prints out exception rest of code is
Description executed
• Prints stack trace
• Terminates the
program
1 //Predict the Output
2 import java.util.*;
3 public class MyClass
4 {
5 public static void main(String args[])
6 {
7 MyClass ob = new MyClass();
8 try
9 {
10 ob.meth1();
11 }
12 catch(ArithmeticException e)
13 {
14 System.out.println("ArithmaticException thrown by meth1()
15 method is caught in main() method");
16 }
17 }
18
19
20
21
22
1 public void meth1()
2 {
3 try
4 {
5 System.out.println(100/0);
6 }
7 catch(NullPointerException nullExp)
8 {
9 System.out.println("We have an Exception - "+nullExp);
10 }
11 System.out.println("Outside try-catch block");
12 }
13 }
14
15
16
17
18
19
20
21
22
1 import java.util.*;
2 public class MyClass {
3 public static void main(String[] args) {
4 try{
5 int arr[]=new int[5];
6 arr[7]=100/0;
7 }
8 catch(ArithmeticException e)
9 {
10 System.out.println("Arithmetic Exception occurs");
11 }
12 catch(ArrayIndexOutOfBoundsException e)
13 {
14 System.out.println("ArrayIndexOutOfBounds Exception occurs");
15 }
16 catch(Exception e)
17 {
18 System.out.println("Parent Exception occurs");
19 }
20 System.out.println("rest of the code");
21 }
22 }
1 //Predict the Output
2 import java.util.*;
3 public class MyClass
4 {
5 public static void main(String[] args)
6 {
7 String[] s = {"Hello", "423", null, "Hi"};
8 for (int i = 0; i < 5; i++)
9 {
10 try
11 {
12 int a = s[i].length() + Integer.parseInt(s[i]);
13 }
14 catch(NumberFormatException ex)
15 {
16 System.out.println("NumberFormatException");
17 }
18
19
20
21
22
1 catch (ArrayIndexOutOfBoundsException ex)
2 {
3 System.out.println("ArrayIndexOutOfBoundsException");
4 }
5 catch (NullPointerException ex)
6 {
7 System.out.println("NullPointerException");
8 }
9 System.out.println("After catch, this statement will be
10 executed");
11 }
12 }
13 }
14
15
16
17
18
19
20
21
22
1 // Pipe(|) operator
2 import java.util.*;
3 public class Main
4 {
5 public static void main(String[] args)
6 {
7 String[] s = {"abc", "123", null, "xyz"};
8 for (int i = 0; i < 5; i++)
9 {
10 try
11 {
12 int a = s[i].length() + Integer.parseInt(s[i]);
13 }
14 catch(NumberFormatException | NullPointerException |
15 ArrayIndexOutOfBoundsException ex)
16 {
17 System.out.println("Handles above mentioned three
18 Exception");
19 }
20 }
21 }
22 }
1 //Predict the output
2 import java.util.*;
3 public class Main
4 {
5 public static void main(String[] args)
6 {
7 try
8 {
9 int i = Integer.parseInt("Thor");
10 }
11 catch(Exception ex)
12 {
13 System.out.println("This block handles all exception types");
14 }
15 catch(NumberFormatException ex)
16 {
17 System.out.print("This block handles NumberFormatException");
18 }
19 }
20 }
21
22
1 //Predict the OUtput
2 import java.util.*;
3 public class Main
4 {
5 public static void main(String[] args)
6 {
7 String[] str = {null, "Marvel"};
8 for (int i = 0; i < str.length; i++)
9 {
10 try
11 {
12 int a = str[i].length();
13 try
14 {
15 a = Integer.parseInt(str[i]);
16 }
17 catch (NumberFormatException ex)
18 {
19 System.out.println("NumberFormatException");
20 }
21 }
22
1 catch(NullPointerException ex)
2 {
3 System.out.println("NullPointerException");
4 }
5 }
6 }
7 }
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
1 //Syntax for finally block Description
2
3 try { It contains all the crucial
4 //Statements that may cause an statements that must be executed
5 exception whether exception occurs or not.
6 }
7 catch {
8 //Handling exception
9 }
10 finally {
11 //Statements to be executed
12 }
13
14
15
16
17
18
19
20
21
22
1 public class MyClass{
2 public static void main(String args[]){
3 try{
4 int data = 30/3;
5 System.out.println(data);
6 }
7 catch(NullPointerException e)
8 {
9 System.out.println(e);
10 }
11 finally
12 {
13 System.out.println("finally block is always executed");
14 }
15 }
16 }
17
18
19
20
21
22
1 public class MyClass
2 {
3 public static void main(String args[]) {
4 try{
5 int num=121/0;
6 System.out.println(num);
7 }
8 catch(ArithmeticException e){
9 System.out.println("Number should not be divided by zero");
10 }
11 finally{
12 System.out.println("This is finally block");
13 }
14 System.out.println("Out of try-catch-finally");
15 }
16 }
17
18
19
20
21
22
1 public class MyClass
2 {
3 public static void main(String args[])
4 {
5 System.out.println(MyClass.myMethod());
6 }
7 public static int myMethod()
8 {
9 try
10 {
11 return 0;
12 }
13 finally
14 {
15 System.out.println("This is Finally block");
16 System.out.println("Finally block ran even after return
17 statement");
18 }
19 }
20 }
21
22
1 public class MyClass
2 {
3 public static void main(String args[])
4 {
5 System.out.println(MyClass.myMethod());
6 }
7 public static int myMethod()
8 {
9 try
10 {
11 return 0;
12 }
13 finally
14 {
15 System.out.println("This is Finally block");
16 System.out.println("Finally block ran even after return
17 statement");
18 }
19 }
20 }
21
22
Cases when the finally block doesn’t execute
If the length of the string is > 2 then call user defined function splitString() and print
the split string along with index.
Complete the function power in class MyCalculator and return the appropriate result
after the power operation or an appropriate exception as detailed above.
Question 2
Sample Input: Sample Output:
35 243
24 16
00 java.lang.Exception: n and p should
-1 -2 not be zero.
-1 3 java.lang.Exception: n or p should not
be negative.
java.lang.Exception: n or p should not
be negative.
1 import java.util.Scanner;
2 class MyCalculator {
3 public static int power(int n,int p) throws Exception
4 {
5 if(n<0 || p<0)
6 {
7 throw new Exception ("n or p should not be negative.");
8 }
9 else if(n==0 && p==0)
10 {
11 throw new Exception ("n and p should not be zero.");
12 }
13 else
14 {
15 return((int)Math.pow(n,p));
16 }
17 }
18 }
19
20
21
22
1 public class Solution {
2 public static final MyCalculator my_calculator = new MyCalculator();
3 public static final Scanner in = new Scanner(System.in);
4 public static void main(String[] args) {
5 while (in .hasNextInt()) {
6 int n = in .nextInt();
7 int p = in .nextInt();
8
9 try {
10 System.out.println(my_calculator.power(n, p));
11 } catch (Exception e) {
12 System.out.println(e);
13 }
14 }
15 }
16 }
17
18
19
20
21
22
MCQ
1 // Predict the output
2 public class Test{
3 public static void main(String args[]){
4 try{
5 int i;
6 return;
7 }
8 catch(Exception e){
9 System.out.print("CatchBlock");
10 }
11 finally{
12 System.out.println("FinallyBlock");
13 }
14 }
15 }
16
17
18
19
20
21
22
Question 1
A) CatchBlock
B) CatchBlock FinallyBlock
C) FinallyBlock
D) No Output
1 // Predict the output
2 class Bike{
3 public void petrol() {}
4 }
5 public class Test{
6 public static void main(String args[]){
7 Bike fz = null;
8 try{
9 fz.petrol();
10 }
11 catch(NullPointerException e){
12 System.out.print("There is a NullPointerException. ");
13 }
14 catch(Exception e){
15 System.out.print("There is an Exception. ");
16 }
17 System.out.print("Everything went fine. ");
18 }
19 }
20
21
22
Question 2
A) There is a NullPointerException. Everything went fine.
B) There is a NullPointerException.
D) This code will not compile, because in Java there are no pointers.
1 // Predict the output
2 public class MyClass{
3 public static void main(String args[]){
4 try{
5 String arr[] = new String[10];
6 arr = null;
7 arr[0] = "one";
8 System.out.print(arr[0]);
9 }
10 catch(Exception ex)
11 {
12 System.out.print("exception");
13 }
14 catch(NullPointerException nex)
15 {
16 System.out.print("null pointer exception");
17 }
18 }
19 }
20
21
22
Question 3
A) "one" is printed.
D) "exception" is printed.
1 // Predict the output
2 import java.lang.Exception;
3 public class MyClass{
4 void m() throws Exception {
5 throw new java.io.IOException("Error");
6 }
7 void n() {
8 m();
9 }
10 void p() {
11 try {
12 n();
13 } catch (Exception e) {
14 System.out.println("Exception Handled");
15 }
16 }
17 public static void main(String args[]){
18 MyClass obj = new MyClass();
19 obj.p();
20 System.out.println("Normal Flow");
21 }
22 }
Question 4
A) Error
B) Error
Exception Handled
Normal Flow
C) Compilation Error
D) No Output
1 // Predict the output
2 public class MyClass {
3 public static void main(String[] args) {
4 for (int i = 0; i < 3; i++)
5 {
6 try
7 {
8 execute(i);
9
10 }
11 catch (Exception e) {
12 }
13 System.out.print("-");
14 }
15 }
16
17
18
19
20
21
22
1 public static void execute(int i) {
2 p('S');
3 try {
4 p('H');
5 t(i == 1);
6 try{
7 p('A');
8 t(i == 3);
9 }
10 finally {
11 p('R');
12 }
13 }
14 catch (Exception e) {
15 p('K');
16 t(i == 3);
17 }
18 }
19
20
21
22
1 public static void p(char c)
2 {
3 System.out.print(c);
4 }
5 public static void t(boolean thrw)
6 {
7 if (thrw)throw new RuntimeException();
8 }
9 }
10
11
12
13
14
15
16
17
18
19
20
21
22
Question 5
A) SHARK-SH-SHK-
B) SHAR-SHK-SHAR-
C) Compilation Error
D) SHARK-SHARK-SHARK-
THANK YOU