Java Programming Help- Throwing and Catching an Exception - java

I have a Java assignment and I need help at this point. Below is the requirement:
Create a WindowMalfunction and PowerOut Events to simulate problems that may occur in a GreenhouseControls. The event should set the following boolean variables as appropriate in GreenhouseControls:
windowok = false;
poweron = false;
After setting the variables, WindowMalfunction or PowerOut should throw an exception specifying the faulty condition. Create a ControllerException class that extends Exception for this purpose.
If an exception is thrown from WindowMalfunction or PowerOut, the Controller catches the exception, then initiates an emergency shutdown with an appropriate message. Add a method to Controller called shutdown, and override this method in GreenhouseControls to accomplish the shutdown.
I have created the ControllerException class:
public class ControllerException extends Exception{
public ControllerException(String except){
super(except);
}
public String getMessage(){
return super.getMessage();
}
public void shutdown(){
}
}
Now I have to implement it in the GreenHouseControls class. This is what I have done:
public class WindowMalfunction extends Event{
ControllerException newExcep= new ControllerException("Error:");
public WindowMalfunction(long delayTime) {
super(delayTime);
}
public void action() throws ControllerException {
}
}
Now, in the action() method of the WindowMalfunction I need to actually throw the ControllerException that I have created. Then, I will need to catch the exception in the Controller.run method.
public void run() throws ControllerException {
while(eventList.size() > 0)
// Make a copy so you're not modifying the list
// while you're selecting the elements in it:
for(Event e : new ArrayList<Event>(eventList)) {
if(e.ready()) {
System.out.println(e);
e.action();
eventList.remove(e);
}
}
}
How do I go about doing so?
Thanks.

In the action() method you can do something like this to throw the exception you just created
throw new ControllerException();
And in run() method put the call to action() method in try-catch block something like
try{
action()
}
catch(ControllerException ex){
System.out.println("Woho caught the exception");
}

Related

Exception in child thread

I am creating a new Thread from the main thread using the below:
public static void main(String[] args) {
try {
new TestThread().start();
} catch (Exception e) {
e.printStackTrace();
}
System.out.println("Inside main");
}
And throwing an exception. I am able to catch it in the main thread also.But according to article
this shouldn't be the case right?
EDIT:
public class TestThread extends Thread {
#Override
public void run() {
throw new RuntimeException();
}
}
Exception Trace
Inside main
Exception in thread "Thread-0" java.lang.RuntimeException
at TestThread.run(TestThread.java:8)
Exceptions thrown by a thread's run() method, are not caught by the main thread but handled by the JVM.
If you want to manage this situation, you should use the Thread.setUncaughtExceptionHandler method.
Something like this:
class MyHandler implements Thread.UncaughtExceptionHandler
{
#Override
public void uncaughtException(Thread t, Throwable e)
{
System.out.println("Caught exception " + e.getMessage());
e.printStackTrace();
}
}
class MyThread extends Thread
{
public MyThread()
{
setUncaughtExceptionHandler(new MyHandler());
}
#Override
public void run()
{
throw new RuntimeException("ciao");
}
}
The article you refer to is "Java Thread: Run method cannot throw checked exception".
In Java, Thread's run method cannot throw checked exceptions because it would involve changing the signature of the run() method. However, in your example, you throw a RuntimeException, which isn't a checked exception. See Understanding checked vs unchecked exceptions in Java.
Note, however, that you are not actually catching the exception in the main thread: replace the printStackStrace statement with something like ...println("caught") for this to be more obvious.

Using throws keyword and handling it in the main rather than handling it in the method in which it occurs

If I add the throws keyword in the method signature and handle it in my main() inside my TestClass{}, is it a good approach or should I handle the exception in the method in which it occurs fooBar(), which approach is recommended or what are the trade-offs between the two. Sorry this question might seem a little weird, just a newbie in Java.
public class Foo {
//private fields
public Foo() {
//ctor
}
//accessors and mutators
//method that throws exception
public void fooBar() throws FooBarException {
throw new FooBarException();
}
}
Generally, the scope of try block should be as small as possible.
public void fooBar(){
try{
//Lines that can through error
}
catch (FileNotFoundException e) {
//Handle exception Here
//e.printStackTrace();
/*
other code that will not throw any error
*/
}
or if the whole block may throw the error then
public void fooBar() throws FooBarException {
}
//Handle in the exception where you calling the method

JAVA: Can I enforce only one thread creation?

Is there a way to enforce only a single execution of a thread object?
Something like a thread singleton?
To illustrate, consider below example:
I have a runnable implemented class.
I would like that I will be able to call start() method only one time of the object.
You can put a boolean as attribute to check if the thread has already been launch
Add a static boolean field in your Runnable and check it at the start of the run method like this:
synchronized(MyRunnable.class) {
if(alreadyRan) {
return;
}
alreadyRan = true;
}
Well, with the tips of my friends here in this thread, I reached the following:
public class TestThread extends Thread {
static private TestThread _instance = null;
private TestThread() {}
public static TestThread getThread(){
if(_instance == null)
_instance = new TestThread();
return _instance;
}
#Override
public void run()
{
System.out.println("Hello");
}
}
And this is an example of using it, when calling start for the second time throws an exception:
public class Main {
public static void main(String[] args) {
try {
TestThread.getThread().start();
TestThread.getThread().start();
} catch (IllegalThreadStateException e) {
System.out.println("Error: Tried to start more than one instance of this thread!");
e.printStackTrace();
}
}
}
Your comments are welcomed.

Java exception specification for the main method

Do we not need exception specification for the main method in a Java program. For example, the following code works exactly the same without specifying "throws Xcept" for the main method.
class Xcept extends Exception {
public Xcept(){
}
public Xcept(String msg){
super(msg);
}
}
public class MyException {
public void f() throws Xcept {
System.out.println("Exception from f()");
throw new Xcept("Simple Exception");
}
public static void main(String[] args) throws Xcept {
MyException sed = new MyException();
try {
sed.f();
} catch(Xcept e) {
e.printStackTrace();
}
finally {
System.out.println("Reached here");
}
}
}
I read that java enforces this, but I don't get a compile time error if I exclude this specification for the main method.
That's because Xcept will never be thrown out of your main method, as you actually catch it there... The sed.f() call may result in an Xcept being thrown, but it's caught and handled.

Access Try-Catch block's code in another class

May be it could be silly,but I want to clear my the technical understanding of this code:
import netscape.*;//ldap jar
public class A {
public void method() {
...
try {
//code is written here.
LDAPSearchResults lsr = ldi.search(LDAPConnectionInfo.MY_SEARCHBASE,LDAPConnectionInfo.MY_SCOPE,LDAPConnectionInfo.MY_FILTER,null,false);
while(lsr.hasMoreElements()){
LDAPEntry findEntry = (LDAPEntry)lsr.nextElement();
} catch(...) {
}
}
}
Now I call another class
public class B {
A a = new A();
//here I want to use attributeName
}
How could I access A class's member(in try block) in B class.
Any way to handle try block code for reuse in another class.
How could I handle all those exception in another class.
Any modification should I need...
Calling method of Object type.
public class C{
private String attributeName;
public String getAttributeName() {
return attributeName;
}
public Object method(){
attributeName=lAttribute.getName();
}
}
How could print this Object type method into String(in a jsp page)... any inputs
You'll need a member in class A and a getter:
public class A {
private String attributeName;
public String getAttributeName() {
return attributeName;
}
public void method(){
...
try {
//code is written here.
attributeName = lAttribute.getName();
}
catch() {
}
}
}
Then:
public class B {
A a = new A();
// somewhere
String str = a.getAttributeName();
}
There's no way to access a method's private variables like you did in the original example, as they only exist on the stack during the method call.
Edit: I noticed another question:
How could I handle all those exception in another class.
I assume you want to call your method somewhere else and catch the exceptions there. In that case you can use the throws keyword to communicate that your method will pass exceptions to the caller:
public class A {
public void method() throws IOException {
//code is written here.
String attributeName = lAttribute.getName();
}
public void anotherMethod() {
try {
method();
} catch(IOException ex) {
...
}
}
}
then if some other piece of code calls method it will be forced to either handle or further propagate the exception.
How could I handle all those exception in another class.
In your calling class you can catch Throwable (which will catch all exceptions and errors)
try {
....
}
catch (Throwable t) {
//do something with the throwable.
}
if you do not want to catch Errors (Ive only done this when messing around with ImageIO and had memory problems) in Java then catch Exception instead
Any way to handle try block code for reuse in another class
here you could create a method in another class and then call it within your try /catch block
public class XYX {
public void methodForTry() throws Exception {
//do something
}
}
try {
new XYZ().methodForTry();
}
catch (Exception e){
}
You may or may not want to create new XYZ here. It depends what state this object may or may not hold.
As to the last questions I think Tudor's answer covers this
Your question may be about extracting the code template
try { ... do stuff ... }
catch (MyFirstException e) { ...handle ... }
catch (MySecondException e) { ...handle ... }
... more catch ...
Where you only want to change the ... do stuff ... part. In that case you'd need closures, which are coming with Java 8, and today you'd need something quite cumbersome, of this sort:
public static void tryCatch(RunnableExc r) {
try { r.run(); }
catch (MyFirstException e) { ...handle ... }
catch (MySecondException e) { ...handle ... }
... more catch ...
}
where RunnableExc would be an
interface RunnableExc { void run() throws Exception; }
and you'd use it this way:
tryCatch(new RunnableExc() { public void run() throws Exception {
... do stuff ...
}});
why not return it?
public String method() {
String attributeName
try {
//code is written here.
attributeName = lAttribute.getName();
} catch(...) {
}
return attributeName;
}
public class B {
A a = new A();
String attributeName = a.method();
}

Categories