Exceptions creation and handling

Page 1

hamzamac@live.com http://issuu.com/hamzamac

College Of Informatics and Virtual Education

NAME: Makame, Makame H PROGRAM: B Sc. Computer and Information Security COURSE NAME: Object Oriented Programing in Java COURSE CODE: CS 207 PART: Exceptions creation and handling

Problem Descriptions: This program code demonstrates on how to create your own exception and catching it. 

First: there should be a class that extends Exception class, containing o A constructor that explicitly calls its super constructor while passing the appropriate error message. Second: a method that throws an exception o It creates and throws a new exception that is an object of the class that extends Exception class. o The thrown exception is returned to the caller (the method in the try block). Third: the try-catch block handles the exception as follows o The try block execution is stopped once an exception is detected and executes the appropriate catch method (catch block). o The catch method passes an object of the exception class o The object is used to display a message using getMessage() that is inherited by every throwable class.

Tuesday, March 13, 2012


hamzamac@live.com http://issuu.com/hamzamac import java.util.*;

public class Rapunzel{ public static void main(String[] args){ Rapunzel object1=new Rapunzel(); Scanner s=new Scanner(System.in);

try{ String yourGuess; System.out.println("Who look like Repunzel at CIVE"); yourGuess=s.next(); object1.comb(yourGuess); // the above method returns/throws an exception if the guess is wrong.

}catch(CombException ce) { System.out.println("Oh noo! "+ ce.getMessage()); //display a message //ce.printStackTrace(); }

}

public void comb(String n) throws CombException{ if(n.equals("nabila")){ System.out.println("You are correct!"); } else{ throw new CombException(); }

} }

Tuesday, March 13, 2012


hamzamac@live.com http://issuu.com/hamzamac

class CombException extends Exception{ public CombException(){ super("Can’t you even guess her name?!"); } }

Tuesday, March 13, 2012


Turn static files into dynamic content formats.

Create a flipbook
Issuu converts static files into: digital portfolios, online yearbooks, online catalogs, digital photo albums and more. Sign up and create your flipbook.