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
Related
I got a method that prints out the animals' names.
I now need an error to be printed out if the id is not one of the given ones.
How does it work?
class Methode {
static final int DEER = 0;
static final int BIRD = 1;
static final int COW = 2;
static final int PIG = 3;
public static void main(String[] args) {
printAnimal();
}
public static void printAnimal (int id) {
if (id == DEER) {
System.out.println("Deer");
}
else if (id == BIRD) {
System.out.println("Bird");
}
else if (id == COW) {
System.out.println("COW");
}
else if (id == PIG) {
System.out.println("Pig");
}
}
}
If by error you mean an Exception (otherwise I don't know why you didn't simply printed an "error" message like you did in your else if branches), then you need to create a custom class which extends Exception and throw it in a new else branch. Here is an example:
Exception:
public class NoSuchAnimalException extends Exception {
public NoSuchAnimalException(String message) {
super(message);
}
}
Test:
public static void printAnimal(int id) throws NoSuchAnimalException {
if (id == DEER) {
System.out.println("Deer");
} else if (id == BIRD) {
System.out.println("Bird");
} else if (id == COW) {
System.out.println("COW");
} else if (id == PIG) {
System.out.println("Pig");
} else {
throw new NoSuchAnimalException("No such animal");
}
}
public static void main(String[] args) {
try {
printAnimal(6);
} catch (NoSuchAnimalException e) {
System.out.println(e.getMessage());
}
}
The exception will be thrown in the last else (the id provided in method call doesn't meet the previous requirements) and will be handled in the public static void main() method.
Firstly you call your printAnimal() method without a parameter. That's no good.
Secondly, there are two kinda of exceptions in Java, checked and unchecked. You need to consider which kind you're working with.
Checked means your function must be declared by:
methodName() throws SomeException{
...}
And accordingly a caller MUST catch exceptions.
Unchecked means you can throw the exception without doing this, but other programmers aren't made aware of (and conversely, not forced to handle) any exceptions thrown.
Exceptions should be created, like classes, inheriting the base type of exception appropriate.
Checked exception
class someException extends exception{...}
Unchecked exception
class someException extends RuntimeException{...}
For non custom exceptions they are thrown like so:
The checked exception
throw new Exception ('message');
The unchecked exception
throw new RuntimeException ('message');
Please read the Java doc on exceptions.
Exceptions are an important part of OOP
(This was written on a phone, so there might be a few typos etc.)
Should use enums and switch for this task:
public class Methode {
public enum Animal {
DEER (0),
BIRD (1),
COW (2),
PIG (3);
private final int value;
private static Map valueMap = new HashMap<>();
Animal(int value)
{
this.value = value;
}
static {
for (Animal enumVal : Animal.values()) {
valueMap.put(enumVal.value, enumVal);
}
}
public static Animal valueOf(int animalId) {
return (Animal) valueMap.get(animalId);
}
public int getValue()
{
return value;
}
}
public static void main(String[] args) throws Exception {
printAnimal(1);
}
public static void printAnimal (int id) throws Exception {
Animal animal = Animal.valueOf(id);
if(animal == null) {
throw new Exception("Animal not found"); //better use own exception
} else {
switch (animal) {
case DEER:
System.out.println("Deer");
break;
case BIRD:
System.out.println("Bird");
break;
case COW:
System.out.println("COW");
break;
case PIG:
System.out.println("Pig");
break;
default:
System.out.println(animal.name());
}
}
}
}
I'm sending more than 1 request to a web service, below there is an example of that requests. Its important for my application to get the answer from the web service so if there is an exception application will try couple of times to get the answer.
Because of that getting something simple like
deviceList = serviceAdapter.getDevices(); is turn into below code.
boolean flag = true;
int counter = 1;
List<Device> deviceList = null;
while (flag) {
try {
deviceList = serviceAdapter.getDevices();
flag = false;
} catch (Exception e) {
try {
if (counter == 5) {
System.out.println("Timeout Occured!");
flag = false;
} else {
Thread.sleep(1000 * counter);
counter++;
}
} catch (InterruptedException e1) {
}
}
}
And in my application i have lots of requests which means there will be more ugly codes. Is there a way where i will call my request methods as parameter for another method something like this:
deviceList = wrapperMethod(serviceAdapter.getDevices());
Problem is there will be different type of requests, so they will return different type objects (list,array,string,int) and their paramaters will change. Is there a suitable solution in java for this problem?
You can pass a Supplier<T> to the wrapperMethod:
public static <T> T wrapperMethod (Supplier<T> supp) {
boolean flag = true;
int counter = 1;
T value = null;
while (flag) {
try {
value = supp.get();
flag = false;
} catch (Exception e) {
try {
if (counter == 5) {
System.out.println("Timeout Occured!");
flag = false;
} else {
Thread.sleep(1000 * counter);
counter++;
}
} catch (InterruptedException e1) {
}
}
}
}
And call it with:
List<Device> deviceList = wrapperMethod (() -> serviceAdapter.getDevices());
I'm afraid, though, that it will limit the methods you call within the lambda expression to throw only RuntimeExceptions.
You can use some command implementation to execute some specific codes :
Here is a simple example of a command
interface Command{
void run();
}
And a couple of implementations :
class SayHello implements Command{
#Override
public void run() {System.out.println("Hello World");}
}
class KillMe implements Command{
public void run() { throw new RuntimeException();};
}
All we have to do to execute those method is to receive an instance of Command and run the method :
public static void execCommand(Command cmd) {
cmd.run();
}
And to use this
public static void main(String[] args) {
execCommand(new SayHello());
execCommand(new KillMe());
}
Hello World
Exception in thread "main" java.lang.RuntimeException
It also accepts lambda expression :
execCommand(() -> System.out.println("Say goodbye"));
And method reference :
public class Test{
public static void testMe() {
System.out.println("I work");
}
}
execCommand(Test::testMe);
Note that I didn't specify that this could throw Exception so I am limited to unchecked exception like RuntimeException but of course void run() throws Exception could be a solution. That way you can do what ever you want.
Full example (with exceptions) :
public class Test {
public static void main(String[] args) {
try {
execCommand(new SayHello());
execCommand(() -> System.out.println("Say goodbye"));
execCommand(Test::testMe);
execCommand(new KillMe());
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public static void testMe() throws IOException{
System.out.println("I work");
}
public static void execCommand(Command cmd) throws Exception {
cmd.run();
}
}
interface Command{
void run() throws Exception;
}
class SayHello implements Command{
#Override
public void run() {System.out.println("Hello World");}
}
class KillMe implements Command{
public void run() { throw new RuntimeException();};
}
Output:
Hello World
Say goodbye
I work
Exception in thread "main" java.lang.RuntimeException
at main.KillMe.run(Test.java:39)
at main.Test.execCommand(Test.java:25)
at main.Test.main(Test.java:17)
You can use #RetryOnFailure annotation from jcabi-aspects
Create a wrapper method then annotate it to enable auto retry upon Exception
As an example:
#RetryOnFailure(attempts = 5)
List<Device> retryWhenFailed(ServiceAdapter serviceAdapter) throws Exception {
return serviceAdapter.getDevices();
}
This solution uses Generics to be able to handle different Object with most of the same code and a Runnable to execute the fetching.
With this solution, you would need only to write the different adapters extending from ServiceAdapter<T extends Fetchable> to implement the logic to fetch the data for each different class (which would have to implement Fetchable).
Define an interface that abtracts the objects that can be fetched by the different services.
package so50488682;
public interface Fetchable {
}
The ojbect that are to be retrieved implement this interface so you can use the same code for different classes.
package so50488682;
public class Device implements Fetchable{
private String id;
public Device(String id) {
this.id = id;
}
public String toString() {
return "I am device " + id;
}
}
Define an abstract ServiceAdapter that the different service adapters will extend to implement the logic for each kind of object to be retrieved. We add throws Exception to the get() method so this method cand just delegate the exception handling to the FetcherService and decide if it should retry or fail.
package so50488682;
import java.util.List;
public abstract class ServiceAdapter<T extends Fetchable> {
public abstract List<T> get() throws Exception;
}
This is an example of an implementation done to get objects of class Device.
package so50488682;
import java.util.ArrayList;
import java.util.List;
public class DeviceServiceAdapter extends ServiceAdapter<Device>{
#Override
public List<Device> get() throws Exception{
List<Device> rtn = new ArrayList<>();
// fetch the data and put it into rtn, this is a mock
Device d = new Device("1");
rtn.add(d);
d = new Device("2");
rtn.add(d);
d = new Device("3");
rtn.add(d);
//
return rtn;
}
}
Finally this is a generic solution to run the different service adapters.
public class FetcherService<T extends Fetchable> implements Runnable{
List<T> result = new ArrayList<>();
ServiceAdapter<T> serviceAdapter;
#Override
public void run() {
boolean flag = true;
int counter = 1;
while (flag) {
try {
result = serviceAdapter.get();
flag = false;
} catch (Exception e) {
try {
if (counter == 5) {
System.out.println("Timeout Occured!");
flag = false;
} else {
Thread.sleep(1000 * counter);
counter++;
}
} catch (InterruptedException e1) {
throw new RuntimeException("Got Interrupted in sleep", e);
}
}
}
}
public List<T> getResult() {
return result;
}
public void setResult(List<T> result) {
this.result = result;
}
public void setAdapter(ServiceAdapter<T> adapter) {
this.serviceAdapter = adapter;
}
}
From the main or calling program it work like this:
package so50488682;
import java.util.List;
public class SO50488682 {
public static void main(String args[]) {
try {
DeviceServiceAdapter deviceServiceAdapter = new DeviceServiceAdapter();
FetcherService<Device> deviceFetcherService = new FetcherService<>();
deviceFetcherService.setAdapter(deviceServiceAdapter);
deviceFetcherService.run();
List<Device> devices = deviceFetcherService.getResult();
for(Device device : devices) {
System.out.println(device.toString());
}
}catch(Exception e) {
System.out.println("Exception after retrying a couple of times");
e.printStackTrace();
}
}
}
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!");
}
}
I am facing problems when using try/catch
I created an exception class called EmptyQueueException that extends from Exception
Unfortunately, Eclipse throws me an error :" Catched expected instead"
public class Testclass {
public static void main(String[] args) {
ArrayQueue arrayy = new ArrayQueue();
try{
arrayy.dequeue();
}
catch(EmptyQueueException s){
// what to do here ?
}
} // end main
} // end testclass
Here is my Exception class:
public class EmptyQueueException extends Exception {
// automatically done by eclipse, what for?
private static final long serialVersionUID = 1L;
public EmptyQueueException() {
}
public EmptyQueueException(String s){
super("Queue is empty");
}
}
This is my dequeue method:
public int dequeue() throws EmptyQueueException {
if (empty()){
throw new EmptyQueueException();
}
int retour = head();
head = ++head % array.length;
return retour;
}
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
}
}