i am a new in java .please help me . i want to implement exception using inheritance . i want to make a super class say ExceptionA and two sub classes ExceptionB and ExceptionC . i want to write a program that catches exception with super class.ExceptionB class inherit from ExceptionA class and ExceptionC class inherit form ExceptionB.i also want that my code must demonstrate that the catch block for type ExceptionA catches exceptions of types ExceptionB and ExceptionC.
i try my best but in vain.code is here
package assignment.solution;
/**
*
* #author abc
*/
public class ExceptionA {
//code for Arithmetic eception
public static void method2() throws ArithmeticException{
int x=4;
int y=0;
int z=x/y;
}
public static void method1(){
try{
method2();
}
catch(ArithmeticException ex){
System.out.println("divide by zero occured");
}
}
public static void main(String[] args) {
ExceptionA.method1();
}
}
class ExceptionB extends ExceptionA{
// i want to show here that catch block of parent class work here
}
catch (ArithmeticException eex){
super.method1();
}
All exception in Java belongs to the superclass Exceptions.
In order to create an exception class, you must create a class which extends the super class.
class MyException extends Exception{
}
Now if you want another class that inherits MyException. Well, you simply declare a new class that extends MyException.
class MyException2 extends MyException{
}
Related
I have two classes inheriting from java.lang.Exception. They both have a method with the same signature void a(){...}. They both can be thrown in a code block. If I do:
catch (SubException1 | SubException2 e)
{
e.a();
}
Then it won't compile because method a() does not belong to Exception. Is it a Java language flaw? How should I design my code properly to prevent code redundancy?
When you catch multiple exception types in a single catch statement the inferred type of the caught exception is the greatest common denominator of those classes. In your case, the greatest common denominator is Exception, which doesn't have the method void a(). In order to make it accessible to the catch block you could either extract it to a common base class, or (arguably) more elegantly, define it in an interface that both classes implement:
public interface SomeExceptionInterface {
void a();
}
public class SomeException extends Exception implements SomeExceptionInterface {
// Implementation...
}
public class SomeException2 extends Exception implements SomeExceptionInterface {
// Implementation...
}
If you need to access a method called a(), you need a type that provides that method. A simple solution could be:
public class AbstractSubException extends Exception {
public abstract void a();
}
public class SubException1 extends AbstractSubException {
#Override public void a() { ... }
}
public class SubException2 extends AbstractSubException {
#Override public void a() { ... }
}
Then you can catch the way you did or (somewhat simpler):
catch (AbstractSubException e) {
e.a();
}
Maybe the code for the method a is the same in all sub classes. Then you can make it concrete and put the code into the parent class.
I created my own throwable exception but when i want to throw it, the editor says, that a reference to an enclosing class required. I don't know, what i need to write.
Here's code:
public class Main {
int i = 0;
public Main() {
if (i == 0) throw new MyException("i must not be 0"); //Here it says about enclosing class
}
public static void main(String[] args) throws Exception {
new Main();
}
public class MyException extends Exception {
public MyException(String e) {
super(e);
}
}
}
Someone can tell me, where and what i must write?
You've defined MyException as an inner class of Main, then created an instance of it with no corresponding instance of Main available (since the main method is a static method).
You need to declare the exception class separately, outside of Main. Changing the access from public to package-private would let you keep the declaration in the same file. Otherwise, since you can have only one public class per file, it would need to go in its own file.
Alternatively you can define this as a static inner class, like so:
public class Main {
int i = 0;
public static void main(String[] args) throws Exception {
if (i == 0) throw new MyException("i must not be 0"); //Here it says about enclosing class
}
static class MyException extends Exception {
public MyException(String e) {
super(e);
}
}
}
Making the class static means it does not refer to an instance of the enclosing class.
Either declare MyException class as static
public static class MyException extends Exception {
public MyException(String e) {
super(e);
}
}
Or declare it in its own compilable .java file.
The way you have it now, MyException is an inner class of Main which requires an instance of Main to be initialized.
throw new Main().new MyException("i must not be 0");
After your edit, obviously everything works...
This is a general problem: Your class MyException is a nested class to your Main class, and it will always hold a reference to its enclosing instance. You want to make that exception class static, too.
Alternatively, in general but probably not in this case, you can instantiate the inner class using an instance of the outer class:
Main m = new Main();
throw m.new MyException();
Yes, that’s a new after the dot.
I read this code where the interface throws an exception, but the class which implements it doesn't throw one or catch one, why is that? Is it legal or safe in java?
import java.rmi.*;
public interface MyRemote extends Remote {
public String sayHello() throws RemoteException;
}
import java.rmi.*;
import java.rmi.server.*;
public class MyRemoteImpl extends UnicastRemoteObject implements MyRemote{
public String sayHello() {
return "Server says, 'Hey'";
}
public MyRemoteImpl() throws RemoteException {}
public static void main (String[] args) {
try {
MyRemote service = new MyRemoteImpl();
Naming.rebind("RemoteHello", service);
} catch(Exception ex)
{
ex.printStackTrace();
}
}
}
A general rule of implementing and extending is you can make your new class or interface "less restrictive" but not "more restrictive". If you think of the requirement to handle an exception as a restriction, an implementation that doesn't declare the exception is less restrictive. Anybody who codes to the interface will not have trouble with your class.
— Stan James
As part of the discussion at http://www.coderanch.com/t/399874/java/java/Methods-throwing-Exception-Interface
If a Java method overrides another in a parent class, or implements a method defined in an interface, it may not throw additional checked exceptions, but it may throw fewer.
public class A {
public void thrower() throws SQLException {...}
}
public class B extends A {
#Override
public void thrower() throws SQLException, RuntimeException, NamingException {...}
}
SQLException is fine; it's declared in the overridden method. It could even be replaced by a subclass like SerialException.
RuntimeException is fine; those can be used anywhere.
NamingException is illegal. It isn't a RuntimeException, and isn't in A's list, even as a subtype.
Great answer by #Chetter Hummin.
One way to look at this, and I find it easy to remember, is interface's implementations can be more specific but not more general.
For example in interface void test() throws Exception means "test may throw exception"
then implementation can be void test() means "test will not throw exception" (more specific)
or implementation can be void test() throws NullpointerException (more specific)
interface x {
void testException() throws Exception;
}
public class ExceptionTest implements x {
#Override
public void testException() { //this is fine
}
////// or
#Override
public void testException() throws NullPointerException { // this is fine
}
}
I'm experiment with Generic Classes, and I've run into a hurdle which I cannot overcome. In short, I'm encountering an error which I do not understand why it is being thrown: InstantiationException
In the documentation it defines this exception as:
Thrown when an application tries to create an instance of a class using the newInstance method in class Class, but the specified class object cannot be instantiated because it is an interface or is an abstract class.
Now the problem that has me scratching my head is that I do not use the abstract or interface keyword. I've also heard that it could be due to not having a default constructor (which I have). Just to be sure, I reduced my code to the minimal possible, but still gives an error:
package Sandbox;
public class Sandbox {
public static void main(String[] args) {
Sandbox box = new Sandbox();
}
public Sandbox() {
aMethod(subThread.class);
}
public void aMethod(Class<? extends superThread> type) {
try {
System.out.println("isInterface: "+type.isInterface());
System.out.println("isAssignableFrom of subThread: "+type.isAssignableFrom(subThread.class));
superThread t = type.newInstance();
} catch (InstantiationException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
}
}
private class superThread { // implements Runnable {
public superThread() {}
public void run() {}
}
private class subThread extends superThread {
public subThread() {
super();
}
public void run() {
// more stuff
}
}
}
The Output:
isInterface: false
isAssignableFrom of subThread: true
java.lang.InstantiationException: Sandbox.Sandbox$subThread
at java.lang.Class.newInstance0(Unknown Source)
at java.lang.Class.newInstance(Unknown Source)
at Sandbox.Sandbox.aMethod(Sandbox.java:20)
at Sandbox.Sandbox.<init>(Sandbox.java:11)
at Sandbox.Sandbox.main(Sandbox.java:7)
I'm sure it's quite simple, but I cannot figure this one out. I've tried several things, but nothing has helped. Any and all help is appreciated.
Thanks,
Jon
It's because your inner classes are private. Simple fix:
public static class superThread { // implements Runnable {
public superThread() {}
public void run() {}
}
public static class subThread extends superThread {
public subThread() {
super();
}
public void run() {
// more stuff
}
}
The reasoning is because Class.newInstance must be able to access the constructor for the class you want to create.
Since the class is private, it's not accessible. Also, in order to access a non-static inner class, you essentially have to have an existing instance of the outer class (Sandbox), which newInstance doesn't have. As a result, having either public non-static or private static wouldn't work.
After zjagannatha pointed to the real problem, I also found a fix to my own code that allows me to keep the methods as non-static... essentially I discovered that even though the constructor had zero parameters, Constructor treated it as if it had one. I got it to list the parameter and found it odd that it needed a Sandbox class (I assume the one I'm currently working in) To allow a non-static class, I would need to change my newInstance code to this:
type.getConstructor(this.getClass()).newInstance(this);
and this works as well
I am working on an assignment where I am told that I need to create a class (Call it ClassB) that must extend a given class (Call it ClassA). The only problem is that the code inside of the constructor of ClassA may throw an exception, so when I create my constructor for ClassB, I am trying to wrap a try/catch block around the call to super(), but of course, that doesn't work since super has to be the first call.
How can I work around this?
public ClassB extends ClassA {
public ClassB() throws MyClassAException {
super();
}
}
You can add your exception in the throws clause of your sub class constructor: -
class ClassA {
ClassA() throws Exception {
}
}
public class Demo extends ClassA {
Demo() throws Exception {
super();
}
public static void main(String[] args) {
try {
Demo d = new Demo(); // Handle exception here.
} catch (Exception e) {
e.printStackTrace();
}
}
}
ClassB should have a static method
public static ClassB makeClassB() {
try {
return new ClassB();
}
catch(Exception exc) {
// whatever logic you are currently performing to swallow
// presumably you have some default ClassB to return as part of this logic?
}
that will wrap the construction of ClassB with a try/catch. Client code will call makeClassB() and the constructor to ClassB will be private and throwing.