Exception Handeling In Java: Design and create a Java application that generates
ID: 3886689 • Letter: E
Question
Exception Handeling
In Java:
Design and create a Java application that generates, detects, and handles the following exceptions. Test each scenario with ‘good’ and ‘bad’ data:
a.IndexOutOfBoundsException
b.FileNotFoundException
c.NullPointerException
d.NumberFormatException
e.MyLastNameIsSpelledWrongException – you will need to create this exception class and generate (throw) the error yourself for this one. An example Exception ADT is posted in our 'Resources' and we will demonstrate how to use this.
Explanation / Answer
a.
import java.util.*;
import java.lang.*;
import java.io.*;
class ArrayIndexOutOfBounds
{
public static void main(String args[])
{
int studentmarks[] = { 40, 50, 60 };
try
{
System.out.println(studentmarks[3]);
}
catch(ArrayIndexOutOfBoundsException e)
{
System.out.println("Wrong index number " + e);
}
}
}
Output:
b.
import java.util.*;
import java.lang.*;
import java.io.*;
class FileInput
{
public static void main(String args[])
{
FileInputStream fis = null;
try
{
fis = new FileInputStream("input.txt");
}
catch(FileNotFoundException e)
{
System.out.println("The source file does not exist. " + e);
}
}
}
Output:
c.
import java.util.*;
import java.lang.*;
import java.io.*;
class NullPointer
{
public static void main(String args[])
{
String value = null;
// Checking if ptr.equals null or works fine.
try
{
// This line of code throws NullPointerException
// because ptr is null
if (value.equals("chegg"))
System.out.print("Same");
else
System.out.print("Not Same");
}
catch(NullPointerException e)
{
System.out.print("NullPointerException Caught "+e);
}
}
}
Output:
d.
import java.util.*;
import java.lang.*;
import java.io.*;
class NumberFormat
{
public static void main(String args[])
{
try{
int number1=10, number2=0;
int output=number1/number2;
System.out.println ("Result: "+output);
}
catch(ArithmeticException e){
System.out.println ("You Shouldn't divide a number by zero "+e);
}
}
}
Output:
e.
import java.util.*;
import java.lang.*;
import java.io.*;
class ClassCast
{
public static void main(String args[])
{
try{
List list = new ArrayList();
list.add("abc");
list.add(new Integer(5)); //OK
for(Object obj : list){
String str=(String) obj;
}
}
catch(Exception e){
System.out.println (e);
}
}
}
Output:
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.