Sie sind auf Seite 1von 2

1)write a program that handle an exception that might be thrown by the

following code

public class Main


{
public static void main(String[] args)
{ Int[] a={1,2,0};
Try{
System.out.println(a[3]/a[1]);
}
catch(ArithmeticException ae)
{
Sytem.out.println(An exception occurred:+ae);
}
System.out.println();
}
}

2)
Declare your own java exception class.use this exception class in another
class (hint:use the throws keyword)

public class MyOwnException extends Exception {


public MyOwnException(String msg){
super(msg);
}
}

public class EmployeeTest {


static void employeeAge(int age) throws MyOwnException{
if(age < 0)
throw new MyOwnException("Age can't be less than zero");
else
System.out.println("Input is valid!!");
}
public static void main(String[] args) {
try {
employeeAge(-2);
}
catch (MyOwnException e) {
e.printStackTrace();
}
}
}

3) write a java code that throw and handle NullPointerException

String comparison with literals

A very common case problem involves the comparison between a String variable and a
literal. The literal may be a String or an element of an Enum. Instead of invoking the
method from the null object, consider invoking it from the literal.
// A Java program to demonstrate that invoking a method
// on null causes NullPointerException
import java.io.*;

class GFG
{
public static void main (String[] args)
{
// Initializing String variable with null value
String ptr = null;

// Checking if ptr.equals null or works fine.


try
{
// This line of code throws NullPointerException
// because ptr is null
if (ptr.equals("gfg"))
System.out.print("Same");
else
System.out.print("Not Same");
}
catch(NullPointerException e)
{
System.out.print("NullPointerException Caught");
}
}
}

4) write a java code that throw and handle classnotfoundexception

//package main.java;

public class ClassNotFoundExceptionExample {

private static final String CLASS_TO_LOAD = "main.java.Utils";

public static void main(String[] args) {


try {
Class loadedClass = Class.forName(CLASS_TO_LOAD);
System.out.println("Class " + loadedClass + " found
successfully!");
}
catch (ClassNotFoundException ex) {
System.err.println("A ClassNotFoundException was
caught: " + ex.getMessage());
ex.printStackTrace();
}
}
}

Das könnte Ihnen auch gefallen