Illegal start of expression while throwing an exception? - java

I keep getting the error Illegal start of expression in this part of the code.
switch(length) {
case 1: if(message.equalsIgnoreCase("End")){
throws new AnotherException("Stop",true);
} else {
throws new AnotherException("Continue",false);
}
break;
}
Specifically if I add
throw new AnotherException
Can someone explain the reason why it causes this error? Thanks.

You need to change keyword throws to throw.
When throwing an Exception, throw is used and throws is used in method signatures to indicate expected exceptions from that method.
Change throws new AnotherException("Continue",false); to throw new AnotherException("Continue",false);

Various errors:
your method must handle the exception with throws AnotherException
use throw instead of throws
break statement is unreachable code and wont allow compile because both sides of the if solve throwing an Exception.
So your code must look like:
public static void main(String[] args) throws AnotherException {
String message = "End";
int length = 1;
switch (length) {
case 1:
if (message.equalsIgnoreCase("End")) {
throw new AnotherException("Stop", true);
} else {
throw new AnotherException("Continue", false);
}
}
}

Use throw instead of throws. Throws is used to declare the possibility of a thrown exception after the method head.
yourMethod(...) throws AnotherException {
//stuff....
switch(length)
{
case 1: if(message.equalsIgnoreCase("End")){
throw new AnotherException("Stop",true);
}
else{
throw new AnotherException("Continue",false);
} break;
//stuff...
}

Related

How to handle a runtime error with throws

In the following code snippet, there are cases where the processes cannot handle NullPointerException and IllegalStateException. Namely in the case where I have the input values val=-4 or val=-2.
I read that adding throws after methods' signatures would help. But the code still aborts if I pass the mentioned values over.
public class Test extends Throwable{
public static void processA(int val ) throws NullPointerException, IllegalStateException{
try{
System.out.println("1");
processB(val);
}catch(ArithmeticException e){
System.out.println("2");
}
System.out.println("3");
}
public static void processB(int val) throws NullPointerException, IllegalStateException{
try{
System.out.println("4");
processC(val);
}catch(NullPointerException e){
System.out.println("5");
processC(val+4);
}finally{
System.out.println("6");
}
System.out.println("7");
}
public static void processC(int val)throws NullPointerException, IllegalStateException, ArithmeticException{
System.out.println("8");
if(val<1) throw new NullPointerException();
if(val==1) throw new ArithmeticException();
if(val>1) throw new IllegalStateException();
System.out.println("9");
}
public static void main(String[] args) throws Exception {
processA(1); //processA(-2) or processA(-4)
}
}
It breaks because you are not handling the scenario when a NullPointerException or IllegalStateException is thrown to processA(...). You only handle an ArithmeticException.
Add the following to your code, thereby if any of the three exceptions are thrown, it is handled by method processA.
public static void processA(int val) throws NullPointerException, IllegalStateException {
try {
System.out.println("1");
processB(val);
} catch (ArithmeticException e) {
System.out.println("11");
} catch (NullPointerException e) {
System.out.println("12");
} catch (IllegalStateException e) {
System.out.println("13");
}
System.out.println("3");
}
If you want the caller to handle them then you need to do the same from the caller method. For eg :
public static void main(String[] args) {
try {
processA(12);
} catch (ArithmeticException | NullPointerException | IllegalStateException e) {
// do something here
}
}
To answer your question in the comments: "But why should I use it?"
This will indicate that the caller will need to handle the exception thrown by that method. Now the caller can handle it via a try-catch block or it can re-throw the exception to its caller. The compiler would also give you an error saying that the exception should be handled but this would happen only for checked exceptions. The ones you are throwing are unchecked exceptions. Which means in your case you can pretty much ignore them from the method declaration.
I would suggest you also consider using Thread.UncaughtExceptionHandler in order to make sure you properly handle exceptions which were not properly caught.
Missing out on exception handling is a very common occurrence and can be easily avoided using this API.
References:
How to catch an exception from a thread
Oracle official API
UncaughtExceptionHandler as a best practice

catching java.lang.ArrayIndexOutOfBoundsException

I'm new in Java. Can anyone help me with explanation, why the catch is not catching the MyException (which extends ArrayIndexOutOfBoundsException)?
My example:
public class TestClass {
public static void main(String[] args) {
try{
doTest();
}
catch(MyException me){
System.out.println("MyException is here");
}
}
static void doTest() throws MyException{
int[] array = new int[10];
array[10] = 1000;
}
}
class MyException extends ArrayIndexOutOfBoundsException {
public MyException(String msg){
super(msg);
}
}
The result is:
"Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 10         at TestClass.doTest(TestClass.java:14)         at TestClass.main(TestClass.java:5)"
Why is not "MyException is here"?
Your method actually throws only ArrayIndexOutOfBoundsException.
You catch MyException but that is not what is being thrown, so the catch clause has no effect.
If you wanted to throw MyException you would have to modify the method to catch ArrayIndexOutOfBoundsException and throw MyException instead.
You are confusing the subtype-supertype-relationship.
The code as it is throws an ArrayIndexOutOfBoundsException but not a MyException. Catching the latter will not work because an AIOOBE is not a ME. Your ME is a subtype of AIOOBE.
On the other hand, an AIOOBE has a supertype: IndexOutOfBoundsException. If you have a catch clause for this one, you will get the desired behavior because an AIOOBE is a IOOBE.
Or you could simply throw your ME yourself: throw new MyException(...)
Your doTest method does not throw your custom exception. To throw an exception use
throw new MyException("your message");

How does throws work at Java?

I have been using catch and now I have to use throw.
This is what I 've been given and I can't figure out what's missing so that it will work.
public static void main(String args[]){
Exception_Tester et = new Exception_Tester();
int x1;
int x2;
x1=5;
x2=0;
et.printResults(x1,x2);
}
static void printResults(int a, int b) throws ArithmeticException {
System.out.println("Add: "+(a+b));
System.out.println("Sub: "+(a-b));
System.out.println("Mul: "+(a*b));
System.out.println("Div: "+(a/b));
}
try surrounding the (a/b) in a try statement.
then, in the catch, just throw the exception.
Your printResults method declares that it maight throw an exception of a type ArithmeticException. In order for that to happen something needs to go wrong inside the method, for instance if your b param would be zero an exception would be thrown. If you want to throw exception explicitly you need to use throw statement like this in your method
throw new ArithmeticException();
Before you catch an exception. Your code must throw an exception first. Sometimes there are runtime exceptions, which code itself throws. But sometimes you need a custom Exception to be thrown when some condition gets true. For that you use this throw keyword and throw an exception for your code to Catch it.
Here is a sample
public Object pop() {
Object obj;
if (size == 0) {
throw new EmptyStackException();
}
obj = objectAt(size - 1);
setObjectAt(size - 1, null);
size--;
return obj;
}
It would throw the Exception customly and then you can catch it.
Although if the stack is zero. It might not throw that exception. So you yourself make the code throw that exception for yourself and then handle it somewhere. For that you'll use try { } catch { }.
For more on that: http://docs.oracle.com/javase/tutorial/essential/exceptions/throwing.html
Create a custome exception class and throw the exception from wherever you think it can occur.
public class MyException extends Exception {
public MyException(String message) {
super(message);
}
}
For instance in the division operation in your method. You can use it like..
static void printResults(int a, int b){
if(b == 0 ) {
throw new MyException("Division by Zero");
} else {
System.out.println("Div: "+(a/b));
}
}

needn't to catch the exception in the realization of System.out?

I am new to java, and to make clear of "System.out", i read relevant java source code, then find something i cannot understand.
First the source code of "System.out":
public final static PrintStream out = nullPrintStream();
then i went to nullPrintStream
private static PrintStream nullPrintStream() throws NullPointerException {
if (currentTimeMillis() > 0) {
return null;
}
throw new NullPointerException();
}
My question is: the program may throw a NullPointerException in the function nullPrintStream(), and we needn't to catch the exception in public final static PrintStream out = nullPrintStream();? To make clear of it, i wrote some test codes in Eclipse as follows:
package MainPackage;
public class Src {
private static int throwException() throws Exception{
int m = 1;
if(m == 0) {
throw new Exception();
}
return 0;
}
public static final int aTestObject = throwException(); <==Here i got an error
public static void main(String args[]) {
}
}
Just like i think, i got an error Unhandled exception type Exception, but why System.out is OK without doing with the NullPointerException?
Java has a special class of Exceptions called RuntimeExceptions. They all extend the RuntimeException object, which in turn extends the Exception object. The special thing about a RuntimeException (as opposed to a regular exception) is that it does not need to be explicitly thrown. Several different exceptions fit into this category, such as IllegalArgumentException, IllegalStateException etc...
The advantage of using RTE when you are coding is that you do not need to cover your code with a lot of try/catch/throws statements, especially if the exceptions are expected to be extremely rare and unlikely. Additionally, if you have a general mechanism in place for catching RTE, this will also help make sure your app deals with expection conditions cleanly.
That being said, RTEs can be much more difficult to deal with, as it is not obvious from the signature that a particular class or method will throw that type of exception. Consequently, they are not always a good idea for APIs, unless they are well documented.
A NullPointerException is a RuntimeException, and consequently, does not need to be explicitly declared in the method signature.
NullPointerException is a RuntimeException - it doesn't need to be explicitly caught.
if you make your method do this, it won't bomb on compile:
private static int throwException() throws Exception{
int m = 1;
if(m == 0) {
throw new RuntimeException();
}
return 0;
}
if i adhere to throw Exception() in private static int throwException() , how should i modify public static final int aTestObject = throwException();
You can need to intialise the value in a static block and catch the exception there.
public static final int aTestObject;
static {
try {
aTestObject = throwException(); <==Here i got an error
} catch (Exception e) {
throw new AssertionError(e);
}
}

How does the correct rethrow code look like for this example

Yesterday I red this article about the new Exception Handling in Java 7.
In the article they show an example (No 4) which is not working in Java 6. I just copied it.
public class ExampleExceptionRethrowInvalid {
public static void demoRethrow()throws IOException {
try {
// forcing an IOException here as an example,
// normally some code could trigger this.
throw new IOException("Error");
}
catch(Exception exception) {
/*
* Do some handling and then rethrow.
*/
throw exception;
}
}
public static void main( String[] args )
{
try {
demoRethrow();
}
catch(IOException exception) {
System.err.println(exception.getMessage());
}
}
}
Like in the article descriped it won't compile, because of the type missmatch -throws IOException- and -throw exception-. In Java 7 it will. So my question is.
How do I proper implement this kind of rethrowing of an exception in Java 6? I don't like the suggested implementation example no five. I know it is a matter of taste and problem you try to handle if unchecked exceptions or not. So what can I do to get the -throws IOException- and keep the stack trace? Should I only change the catch to IOException and risk not catching all?
I'm curious about your answers.
Simply catch IOException, like so:
public static void demoRethrow()throws IOException {
try {
// forcing an IOException here as an example,
// normally some code could trigger this.
throw new IOException("Error");
}
catch(IOException exception) {
/*
* Do some handling and then rethrow.
*/
throw exception;
}
}
If the code inside the try block can throw a checked exception other than IOException, the compiler will flag this up as an error, so you're not "risk[ing] not catching all".
If you're also interested in unchecked exceptions, you could also catch and re-throw RuntimeException (you won't need to declare it in the throws clause).
Catch IOException and everything else separately:
public static void demoRethrow() throws IOException {
try {
throw new IOException("Error");
}
catch(IOException exception) {
throw exception;
}
catch(Exception exception) {
throw new IOException(exception);
}
catch(Exception ex) catches both checked and unchecked (RuntimeException) exceptions.
So to make it functionaly equivalent,
public static void demoRethrow() throws IOException {
try {
throw new IOException("Error");
}
catch(IOException exception) {
throw exception;
}
catch(RuntimeException exception) {
throw new IOException(exception);
}
suffice, and compiler will detect other checked exceptions (good for thinking again about whether they should realy get this far, or should have bean delt with before)
A hacky way to throw to catch a generic exception and rethrow without the compiler checking the exception is to use stop.
public static void demoRethrow() throws IOException {
try {
throw new IOException("Error");
} catch(Throwable t) {
// handle exception
// rethrow the exception without compiler checks.
Thread.currentThread().stop(t);
}
}

Categories