Error when using try catch in Java - java

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;
}

Related

Throwing and catching multiple Exceptions

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

NullPointerException testing ADS method

I'm fairly new to java and I'm trying to test some of my methods in a class but I got the NullPointerException
public class ArrayListTest {
private List ar;
#org.junit.Before
public void setUp() throws Exception {
List ar = new ArrayList();
}
#Test
public void testAdd() throws Exception {
System.out.println(ar);
***ar.add(33);***
The error points at ar.add(33);
java.lang.NullPointerException
at com.company.ArrayListTest.testAdd(ArrayListTest.java:23)
...a bunch of other invokes...
Looking into add method, I can't find anything wrong.
public class ArrayList implements List{
private Object[] elems;
private int nrElems;
public ArrayList() {
nrElems = 0;
elems = new Object[10];
}
public void add(Object e) {
System.out.println(e);
if (nrElems == elems.length) {
resize();
}
elems[nrElems++] = e;
}
Any ideas? The test class is using my own implementation of ArrayList

java catching exception and continue execution

I want to catch an exception, print the place the exception occured and continue running the loop. I have this example code:
public class justcheckin {
static String[] l = {"a","a","b","a","a"};
public class notAexception extends Exception{
private static final long serialVersionUID = 1L;
notAexception (){
super();
}
notAexception(String message){
super(message);
}
}
private void loop () throws notAexception {
notAexception b = new notAexception("not an a");
for (int i = 0; i< l.length; i++){
if (! l[i].equals("a")){
throw b;
}
}
}
public static void main (String[] args) throws notAexception{
justcheckin a = new justcheckin();
a.loop();
}
}
I want to write a warning message, say "index 2 is not a", and continue running the loop.
How can I do it?
Thanks!
I think in your code there is no need to have try catch throw etc.
But still in your same code if you want to perform this,
public class justcheckin {
static String[] l = {"a","a","b","a","a"};
public class notAexception extends Exception{
private static final long serialVersionUID = 1L;
notAexception (){
super();
}
notAexception(String message){
super(message);
}
}
private void loop () throws notAexception {
notAexception b = new notAexception("not an a");
for (int i = 0; i< l.length; i++){
try{
if (! l[i].equals("a")){
throw b;
}
}catch(notAexception ne){
System.out.println("index "+i+" is not a");//index 2 is not a
}
}
}
public static void main (String[] args) throws notAexception{
justcheckin a = new justcheckin();
a.loop();
}
}

Try catch not being forced

I have this Exception:
public class ErrorException extends Exception
{
private static final long serialVersionUID = 1L;
private String errorMessage = "";
private int errorCode = 0;
private String errorLevel = "";
private Window errorSource = null;
public String getErrorMessage()
{
return errorMessage;
}
public int getErrorCode()
{
return errorCode;
}
public String getErrorLevel()
{
return errorLevel;
}
public Window getErrorSource()
{
return errorSource;
}
public ErrorException(String message, int code, int level, Window source)
{
super();
errorMessage = message;
errorCode = code;
switch (level)
{
case 0:
{
errorLevel = "benignError";
}
case 1:
{
errorLevel = "criticalError";
}
case 2:
{
errorLevel = "terminalError";
}
}
errorSource = source;
}
}
And I have this method:
public static Element check(final Document document) throws ErrorException
{
try
{
chapter.resetLatch();
final SecondaryLoop loop = Toolkit.getDefaultToolkit().getSystemEventQueue().createSecondaryLoop();
new Thread()
{
#Override
public void run()
{
SwingUtilities.invokeLater(new Runnable()
{
#Override
public void run()
{
answer.getPreviousElement().takeFocus();
question.removeAnswer(answer);
question.rewriteLetters();
Utils.update(chapter);
loop.exit();
}
});
}
}.start();
loop.enter();
chapter.getLatch().await();
}
catch (InterruptedException e)
{
throw new ErrorException("blankElementDialogError", 8, 1, Main.getGui().getMasterWindow());
}
return new Element();
}
And I use it in this constructor code:
public ConfirmCloseDialog(final Document document, final int postOperation)
{
final CustomJButton doSave = new CustomJButton(Main.getString("doSave"), false);
doSave.addActionListener(new ActionListener()
{
#Override
public void actionPerformed(ActionEvent arg0)
{
getConfirmCloseDialog().dispose();
new Thread()
{
#Override
public void run()
{
/*this method is the one above -->*/Element problem = BlankElementDialog.check(document);
if (problem == null)
{
new SaveChooser(document, postOperation);
}
else
{
new BlankElementDialog(problem);
}
}
}.start();
}
});
}
The code for the second part is not full, but there are no special constructs in the rest of the code (just some GUi objects being constructed and there is no try catch anywhere in the constructor).
However, Eclipse isn't forcing me to encapsulate the method call into try catch block, despite the fact that the method throws an Exception (ErorrException subclasses Exception).
And I know that Exception is checked exception, so it should force it, right?
Why?
What do I have to do so it would force it?
Even without any details Eclipse should notify, look at this:
Just restart the Eclipse should solve the issue.
public class TestClass {
public static void main(String[] args) {
method(2);//Notification here!
}
static void method(int a) throws myException {
}
}
class myException extends Exception {
}

Handling the exception at the calling class itself

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
}
}

Categories

Resources