0% found this document useful (0 votes)
21 views

5-Exception Handling - 1.2 (Creating Own Exception), Java Programming - Arrays and Linked List-29-05

Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
21 views

5-Exception Handling - 1.2 (Creating Own Exception), Java Programming - Arrays and Linked List-29-05

Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 69

Exception Handling

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?

It is the process of responding to the


occurrence during computation of
exceptions.
Exceptional Handling Keywords
•try
•catch
•finally
•throw
•throws
1 import java.util.*; 1 import java.util.*;
2 public class MyClass 2 public class MyClass
3 { 3 {
4 public static void main(String 4 public static void main(String
5 args[]) 5 args[])
6 { 6 {
7 int x=10; 7 int x=10;
8 int y=0; 8 int y=0;
9 int z=x/y; 9 try
10 System.out.println(z); 10 {
11 } 11 int z=x/y;
12 } 12 }
13 13 catch(Exception e)
14 14 {
15 15 System.out.print(e);
16 16 }
17 17 }
18 18 }
19 19
20 20
21 21
22 22
1 import java.util.*; comment/pseudo code/output
2 public class MyClass Output:
3 { java.lang.ArithmeticException: /
4 public static void main(String by zero
5 args[])
6 {
7 int x=10;
8 int y=0; Syntax:
9 try try
10 { {
11 int z=x/y; // Protected code
12 } }
13 catch(Exception e) catch (ExceptionName e1)
14 { {
15 System.out.print(e); // Catch block
16 } }
17 }
18 }
19
20
21
22
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 try{
7 int[] myIntArray = new int[]{1, 2, 3};
8 print(myIntArray);
9 }
10 catch (ArrayIndexOutOfBoundsException e){
11 System.out.println("The array doesn't have fourth element!");
12 }
13 System.out.println("Third line");
14 }
15 public static void print(int[] arr) {
16 System.out.println(arr[3]);
17 }
18 }
19
20
21
22
OUTPUT

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

• The death of a Thread.


• Using of the System. exit() method.
• Due to an exception arising in the finally block.
1 public class MyClass{
2 public static void main(String args[])
3 {
4 System.out.println(MyClass.myMethod());
5 }
6 public static int myMethod(){
7 try {
8 int x = 63;
9 int y = 9;
10 int z=x/y;
11 System.out.println("Inside try block");
12 System.exit(0);
13 }
14 catch (Exception exp){
15 System.out.println(exp);
16 }
17 finally{
18 System.out.println("Java finally block");
19 return 0;
20 }
21 }
22 }
1 public class MyClass{
2 public static void main(String args[])
3 {
4 System.out.println(MyClass.myMethod());
5 }
6 public static int myMethod(){
7 try {
8 int x = 63;
9 int y = 0;
10 int z=x/y;
11 System.out.println("Inside try block");
12 System.exit(0);
13 }
14 catch (Exception exp){
15 System.out.println(exp);
16 }
17 finally{
18 System.out.println("Java finally block");
19 return 0;
20 }
21 }
22 }
1 //Syntax for throw block Description
2
3 The Java throw keyword is used
4 throw new exception_class("error message"); to explicitly throw an
5 exception.
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
1 public class MyClass
2 {
3 public static void validate(int age)
4 {
5 if(age<21 || age>27)
6 throw new ArithmeticException("not eligible");
7 else
8 System.out.println("Eligible to attend Military Selection ");
9 }
10 public static void main(String args[])
11 {
12 validate(30);
13 System.out.println("rest of the code...");
14 }
15 }
16
17
18
19
20
21
22
OUTPUT

Exception in thread "main" java.lang.ArithmeticException: not eligible


at MyClass.validate(MyClass.java:6)
at MyClass.main(MyClass.java:12)
1 public class MyClass
2 {
3 public static void validate(int age)
4 {
5 if(age<21 || age>27)
6 throw new ArithmeticException("not eligible");
7 else
8 System.out.println("Eligible to attend Military Selection ");
9 }
10 public static void main(String args[])
11 {
12 try
13 {
14 validate(30);
15 }
16 catch(ArithmeticException e)
17 {
18 System.out.println(e);
19 }
20 System.out.println("rest of the code...");
21 }
22 }
OUTPUT

java.lang.ArithmeticException: not eligible


rest of the code...
1 public class MyClass
2 {
3 public static void validate(int age)
4 {
5 if(age<21 || age>27)
6 throw new ArithmeticException("not eligible");
7 else
8 System.out.println("Eligible to attend Military Selection ");
9 }
10 public static void main(String args[])
11 {
12 try
13 {
14 validate(21);
15 }
16 catch(ArithmeticException e)
17 {
18 System.out.println(e);
19 }
20 System.out.println("rest of the code...");
21 }
22 }
OUTPUT

Eligible to attend Military Selection


rest of the code...
1 //Syntax for throw block Description
2
3 The Java throw keyword is used
4 return_type method_name() throws to explicitly throw an
5 exception_class_name exception.
6 {
7 //method code
8 }
9
10
11
12
13
14
15
16
17
18
19
20
21
22
1 import java.io.BufferedReader;
2 import java.io.FileNotFoundException;
3 import java.io.FileReader;
4 public class Main {
5 public static void main(String[] args) {
6 Read r = new Read();
7 try {
8 r.read();
9 }
10 catch (Exception e) {
11 System.out.print(e);
12 }
13 }
14 }
15 public class Read {
16 void read() throws FileNotFoundException
17 {
18 BufferedReader bufferedReader = new BufferedReader(new
19 FileReader("F://file.txt"));
20 }
21 }
22
OUTPUT

java.io.FileNotFoundException: F:\file.txt (The system cannot find the


file specified)
1 import java.io.*;
2 class MyMethod {
3 void myMethod(int num)throws IOException, ClassNotFoundException{
4 if(num==1)
5 throw new IOException("IOException Occurred");
6 else
7 throw new ClassNotFoundException("ClassNotFoundException");
8 }
9 }
10 public class MyClass{
11 public static void main(String args[]){
12 try{
13 MyMethod obj=new MyMethod();
14 obj.myMethod(1);
15 }
16 catch(Exception ex){
17 System.out.println(ex);
18 }
19 }
20 }
21
22
OUTPUT

java.io.FileNotFoundException: F:\file.txt (The system cannot find the


file specified)
Throw vs. Throws
throw throws

1. Used to explicitly throw an exception 1. Used to declare an exception

2. Checked exceptions cannot be propagated using


2. Checked exceptions can be propagated
throw only
3. Followed by an instance 3. Followed by a class

4. Used within a method 4. Used with a method signature

5. Cannot throw multiple exceptions 5. Can declare multiple exceptions


Programming
Question 1
Write a program to split the string based on /(slash) symbol in a string. Perform
exception handling and also include finally block which will print "Inside finally
block".

Get a string from the user.

If the length of the string is > 2 then call user defined function splitString() and print
the split string along with index.

Else print the NullPointerException.


Question 1
Sample Input: Sample Output:
Happy/coding/Java Splitted string at index 0 is : Happy
Splitted string at index 1 is : coding
Splitted string at index 2 is : Java
Inside finally block
1 import java.util.*;
2 public class Main
3 {
4 static void splitString(String text)
5 {
6 try
7 {
8 String[] splittedString =text.split("/");
9 for(int i = 0; i < splittedString.length; i++)
10 {
11 System.out.println("Splitted string at index "+i+" is :
12 "+splittedString[i]);
13 }
14 }
15 catch(Exception e)
16 {
17 System.out.println("Exception : "+e.toString());
18 }
19 finally{
20 System.out.println("Inside finally block");
21 }
22 }
1 public static void main(String args[])
2 {
3 Scanner scanner = new Scanner(System.in);
4 String text = scanner.nextLine();
5 if(text.length()>2)
6 {
7 splitString(text);
8 }
9 else
10 {
11 splitString(null);
12 }
13 }
14 }
15
16
17
18
19
20
21
22
Question 2
You are required to compute the power of a number by implementing a calculator.
Create a class MyCalculator which consists of a single method long power(int, int).
This method takes two integers, n and p, as parameters and finds np. If either n or p
is negative, then the method must throw an exception which says “n or p should not
be negative.". Also, if both n and p are zero, then the method must throw an
exception which says “n and p should not be zero."

For example, -4 and -5 would result in java.lang.Exception: n or p should not be


negative

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.

C) There is a NullPointerException. There is an Exception.

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.

B) "null pointer exception" is printed.

C) Compilation fails saying NullPointerException has already been caught.

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

You might also like