Write a program that shows a constructor passing information about constructor failure to an exception handler. Define class SomeClass, which throws an Exception in the constructor. Your program should try to create an object of type SomeClass and catch the ex- ception that’s thrown from the constructor.
How would one add pre and post conditions to this code?
import java.util.Scanner;
public class Demo3 {
public static void main(String[] args) throws Exception{
SomeClass testException;
try
{
testException = new SomeClass();
}
catch(Exception e)
{
System.out.println();
}
}
}
public class SomeClass{
public SomeClass () throws Error {
throw new Exception();
}
}
You should be able to create a constructor that takes two params and throw exception there instead. Also, you can assert some pre and post conditions pro-grammatically if you would like to validate some values. I hope it helps. Your code may look like the following:
public class Demo3 {
public static void main(String[] args){
Scanner scan=new Scanner(System.in);
System.out.println("Enter the firstNumber:");
int a=scan.nextInt();
System.out.println("Enter the secondNumber:");
int b=scan.nextInt();
//you can write some assertion here to meet the pre-conditions
assert(b>0):"You cannot enter a number less or equal to zero";
SomeClass testException;
try
{
testException = new SomeClass(a,b);
}
catch(Exception e)
{
System.out.println("Exception occurred:"+e.getMessage());
}
}
}
public class SomeClass{
int firstNumber;
int secondNumber;
public SomeClass () {
}
public SomeClass (int firstName,int secondName) throws Exception {
//the message to show when you have getMessage() invoked
throw new Exception("Some exception occurrred");
}
}
This does help, Thanks! I've reworked my code though, but I don't understand how to throw an exception when and pre or post condition are not met.
How do I throw an exception, such as an InputMismatchException, when a precondition is not met?
import java.util.Scanner;
public class Demo3 {
public static void main(String[] args){
Scanner scan=new Scanner(System.in);
System.out.println("Enter a number between 0 and 10:");
int a=scan.nextInt();
System.out.println("Enter another number between 0 and 10:");
int b=scan.nextInt();
//assertion here to meet the pre-conditions
assert (a >= 0 && a <= 10) : "bad number: " + a;
assert (b >= 0 && b <= 10) : "bad number: " + b;
SomeClass testException;
try
{
testException = new SomeClass(a,b);
}
catch(Exception e)
{
System.out.println("Exception occurred: "+e.getMessage());
}
}
}
public class SomeClass{
int a;
int b;
public SomeClass () {
}
public SomeClass (int a,int b) throws Exception {
throw new Exception("You've got an error!");
}
}
Related
Hey StackOverflow Community,
I am trying to write code that throws and catches multiple Exceptions that I made.
What might be the problem?
I want to get this output:
Doing risky
Boi
Fooi
Fooi
Fooi
FINAAAL WIN
The main class looks like this:
public class Dorisk {
public static void main(String[] args) {
Dorisk dora = new Dorisk();
try {
dora.Dorisky(1);
}catch(BoinkException bo){
System.out.println("Boi");
}catch(FooException fo){
System.out.println("Fooi");
}catch(BazException ba){
System.out.println("Baaai");
}finally{
System.out.println("FINAAAL WIN");
}
}
public void Dorisky(int x)throws BazException{
while( x < 5 ){
System.out.println("Doing risky");
if(x ==1){
throw new BoinkException();
}
if(x ==2){
throw new BiffException();
}
if(x ==3){
throw new BarException();
}
if(x ==4){
throw new FooException();
}
x++;
}
}
}
And the Exceptions are :
public class BazException extends Exception{
public BazException(){
System.out.println("Baz baja");
}
}
public class FooException extends BazException{
public FooException(){
System.out.println("Foo baja");
}
}
public class BarException extends FooException{
public BarException(){
System.out.println("Bar baja");
}
}
public class BiffException extends FooException{
public BiffException(){
System.out.println("Biff baja");
}
}
public class BoinkException extends BiffException{
public BoinkException(){
System.out.println("Boink baja");
}
}
BUT what I get is:
Doing risky
Baz baja
Foo baja
Biff baja
Boink baja
Boi
FINAAAL WIN
What tells me that only the first Exception in the doRisky method gets thrown, but why?
Thank you for the answers!
Edit: I got it now! The first thrown Exception printed all the other messages, because they were declared in the constructor of the Exception superclasses, and they have to be constructed, so the subclass can run.
Your Dorisky Method throws the exception when x = 1,
means Dorisky method return with BoinkException exception to caller method.
if(x ==1){
throw new BoinkException();
}
First, Why you want to return multiple exceptions?
It is not the right way to design. BTW... I implemented for your understanding.
Here, I created CustomException for each throw and ExceptionList that holds the list of throwable exception.
import java.util.*;
import java.lang.*;
import java.io.*;
/* Name of the class has to be "Main" only if the class is public. */
class Ideone
{
private static ArrayList<Exception> ex = new ArrayList<Exception>();
private static class CustomException extends Exception {
int i;
public CustomException(int i) {
this.i = i;
}
public String toString() {
return "Exception: " + i;
}
}
private static class ExceptionList extends Exception {
ArrayList<Exception> ex = new ArrayList<Exception>();
public ExceptionList(ArrayList<Exception> ex) {
this.ex = ex;
}
public ArrayList<Exception> getEx() {
return ex;
}
}
public static List<Exception> process() throws Exception {
int i = 0;
while(i < 5) {
if(i == 1) {
ex.add (new CustomException(i));
} else if(i==2) {
ex.add (new CustomException(i));
} else if(i==3) {
ex.add (new CustomException(i));
}
i++;
}
if(ex.size() > 0) {
throw new ExceptionList(ex);
} else {
return null;
}
}
public static void main (String[] args) throws java.lang.Exception
{
try {
new Ideone().process();
} catch(ExceptionList ex) {
for(Exception ei : ex.getEx()) {
System.out.println(ei.toString());
}
}
}
}
Output
Exception: 1
Exception: 2
Exception: 3
I have a class constructor and I need to perform a clone. From what I've read the best choice is to use a copy constructor, just like in C++. However, I've got an issue. If my "regular" constructor throws exceptions and such exceptions aren't even possible in a "copy constructor" how to I implement a try-catch if the first statement must be this.
public class X
{
public X() throws MyException
{
}
public X(final X original)
{
try {
this();
} catch (MyException e)
{
}
}
}
Is the only option add throws MyException to copy constructor?
Copy all data to a new instance by constructor could look like this:
public class X
{
// some Fields....
int a, b, c;
public X() { }
public X(final X originalX) throws InvalidArgumentException
{
if(originalX == null) {
throw new InvalidArgumentException("originalX should not be null!");
}
this.a = originalX.getA();
//...
}
// getter-setter....
}
And it´s called like this in main() or where ever else:
// x_1 is filles with Data...
X x_2;
try {
x_2 = new X(x_1);
} catch(InvalidArgumentException ex) {
LOG.reportError(ex.getMessage());
x_2 = new X(); // prevent NullPointer for usage afterwards
}
public class Test {
public static void main(String[] args) throws Exception {
try {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int num = Integer.parseInt(br.readLine().trim());
Object o;
Method[] methods = Inner.class.getEnclosingClass().getMethods();
for(int i=0;i<methods.length;i++) {
System.out.println(methods[i].invoke(new Solution(),8));
}
// Call powerof2 method here
} catch (Exception e) {
e.printStackTrace();
}
}
static class Inner {
private class Private {
private String powerof2(int num) {
return ((num & num - 1) == 0) ? "power of 2" : "not a power of 2";
}
}
}
}
Is it possible to call powerof2() method ?
I am getting java.lang.IllegalArgumentException: argument type mismatch for invoke
Yes, things declared in the same top-level class can always access each other:
public class Test {
public static void main(String[] args) throws Exception {
Inner i = new Inner(); // Create an instance of Inner
Inner.Private p = i.new Private(); // Create an instance of Private through
// the instance of Inner, this is needed since
// Private is not a static class.
System.out.println(p.powerof2(2)); // Call the method
}
static class Inner {
private class Private {
private String powerof2(int num) {
return ((num & num - 1) == 0) ? "power of 2" : "not a power of 2";
}
}
}
}
See Ideone
Reflection version:
public class Test {
public static void main(String[] args) throws InstantiationException, IllegalAccessException, IllegalArgumentException, InvocationTargetException, SecurityException, NoSuchMethodException {
Class<?> privateCls = Inner.class.getDeclaredClasses()[0];
Method powerMethod = privateCls.getDeclaredMethod("powerof2", int.class);
powerMethod.setAccessible(true);
Constructor<?> constructor = privateCls.getDeclaredConstructors()[0];
constructor.setAccessible(true);
Object instance = constructor.newInstance(new Inner());
System.out.println(powerMethod.invoke(instance, 2));
}
static class Inner {
private class Private {
private String powerof2(int num) {
return ((num & num - 1) == 0) ? "power of 2" : "not a power of 2";
}
}
}
}
I have the following example in which I am trying to call a method othermethod() of class otherClass from inside the run method. I have created an object of this otherClass class as "obj" and using it to call the method . But it is throwing up NullPointerException.
Please let me know why is so.
package isAlive;
class MyClass
{
static int ans=0;
void counter () throws InterruptedException
{
System.out.println("----------------------------");
synchronized (this){
System.out.println("----entering>>>>"+this+" " +this.getClass().getName());
for (int i=0;i<=10;i++)
{System.out.println(Thread.currentThread()+" "+i);
Thread.sleep(3000);}
System.out.println("----exit>>>>"+this.getClass().getName()); }
}
}
public class staticSync extends Thread
{
MyClass obj;
otherClass oth;
int num;
staticSync(int n)
{
num=n;
}
staticSync(MyClass m,int n)
{
obj= m;
num= n;
}
public void run()
{
try {
// obj.counter();
oth.othermethod();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public static void main(String ... as)
{try{
// MyClass m1= new MyClass();
// MyClass m2= new MyClass();
staticSync s1= new staticSync(20);
System.out.println("s1--"+s1);
//System.out.println("m1="+m1);System.out.println("m2="+m2);
staticSync s2= new staticSync(15);
System.out.println("s2--"+s2);
staticSync s3= new staticSync(15);
staticSync s4= new staticSync(10);//staticSync s5= new staticSync(m1,10);
s1.start();
s2.start();
}
catch (Exception e)
{}
}
}
class otherClass
{
public synchronized void othermethod()
{
System.out.println("---------------inside othermethod-..>"+this.getClass().getName());
}
}
And the output is :
s1--Thread[Thread-0,5,main]
s2--Thread[Thread-1,5,main]
java.lang.NullPointerException
at isAlive.staticSync.run(staticSync.java:67)
java.lang.NullPointerException
at isAlive.staticSync.run(staticSync.java:67)
Even while using the counter() method i am facing the same problem.
The reason why you're getting a null pointer exception is that you are never assigning a value to oth, and therefore it remains being null from when you declared it.
This
otherClass oth;
^ no value is being assigned
Is basically the same as
otherClass oth = null;
Since it is always null, calling a method from the object throws the error.
I have a function which calls another function in a different class which throws an exception based on the paraameter provided. I want
public class A {
public int f(int p){
{
B obj = new B();
obj.g(p);
}
}
public class B {
public int g(int p)
{
// throws an exception for this value of p
}
}
Is it possible that I can catch the exception in class A itself and handle it ? I can't change the implementation of class B.
Yeah just use a try-catch statement.
public class A {
public int f(int p){
{
B obj = new B();
try {
obj.g(p);
} catch ( /* the exception */ ) {
// handle the exception
}
}
}
public class B {
public int g(int p)
{
// throws an exception for this value of p
}
}