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));
}
}
Related
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...
}
I need to change the return message of the method getMessage() ,
for instance, i have an ArithmeticException, and when i write:
try{c=a/0;}
catch(ArithmeticException excep){System.out.println( excep.getMessage() );}
and I execut this code I have: / by zero.
So, I wanted to change this result by overwriting the getMesage method.
I have created a new class called MyException that inherits from ArithmeticExceprtion and I override the methode getMessage, and after that I have changed the type of the exception in my last code from ArithmeticException to my new name class MyException:
public class MyException extends ArithmeticException{
#override
public String getMessage(){
retun "new code message";}
}
and I have changed the first code, I have wrotten:
try{c=a/0;}
catch(MyException excep){System.out.println( excep.getMessage() );}
and when I have executed this code, I had the same error's message as if I didn't catch the exception:
Exception in thread "main" java.lang.ArithmeticException: / by zero
at main.test.main(Test.java:33)
So, my question is: how can I change the message of the methode getMessage() ?
c=a/0 always throws a ArithmeticException because it's implemented this way.
If you write you're own division function that throws your MyException when dividing by 0 then you can actually catch it:
float division(float a, float b) {
if(b == 0)
throw new MyException();
return a/b;
}
...
try {
c = division(a, b);
} catch(MyException e) {
System.out.println(e.getMessage());
}
If you are using your own defined exception, you have to throw it manually like
throw new MyException();
otherwise it will throw the instance of the class ArithmeticException, so its own getMessage() function will be triggered.
I've got the following method:
public T peek() throws StackEmptyException {
Node<T> tracker = head;
while(tracker.getNext() != null) {
tracker = tracker.getNext();
}
return tracker.getItem();
}
The problem is that when I try to do something like
int firstOne = stack.peek();
I get an unreported exception StackEmptyException and I have no idea what I'm doing wrong at this point. The StackEmptyException has been made in a separate class. Am I suppose to have this class extend that new exception class I made? So confused. Thoughts guys?
Since StackEmptyException is an checked exception (which you shouldn't do in first place), you should handle that exception when invoking the peek() method. The rule is, either you should handle the exception or declare it to be thrown.
However, I would take a step back and change StackEmptyException to an Unchecked Exception. Then you wouldn't need to handle it or declare it as thrown.
Checked exceptions (ie, a class which extends Exception but not RuntimeException or Error) thrown by a method should be handled by this method's caller, recursively so.
Here you have .peek() which throws, say, exception class E (bad name, but this is for illustration). You must do one of the following in a foo() method which calls .peek():
catch it, or
throw it again.
That is, either:
// catch
void foo()
{
try {
peek();
} catch (E e) {
// something
}
}
or:
// throw
void foo() throws E
{
peek();
}
You could even rethrow it:
// catch then rethrow
void foo() throws E
{
try {
peek();
} catch (E e) {
// something, then
throw e;
}
}
I have below class with one method which throws Checked Exception.
public class Sample{
public String getName() throws CustomException{
//Some code
//this method contacts some third party library and that can throw RunTimeExceptions
}
}
CustomException.java
public class CustomException Extends Exception{
//Some code
}
Now in another class i need to call above the method and handle exceptions.
public String getResult() throws Exception{
try{
String result = sample.getName();
//some code
}catch(){
//here i need to handle exceptions
}
return result;
}
My requirement is:
sample.getName() can throw CustomException and it can also throw RunTimeExceptions.
In the catch block, I need to catch the exception. If the exception that is caught is RunTimeException then I need to check if the RunTimeException is an instance of SomeOtherRunTimeException. If so, I should throw null instead.
If RunTimeException is not an instance of SomeOtherRunTimeException then I simply need to rethrow the same run time exception.
If the caught exception is a CustomException or any other Checked Exception, then I need to rethrow the same. How can I do that?
You can do like this :
catch(RuntimeException r)
{
if(r instanceof SomeRunTimeException)
throw null;
else throw r;
}
catch(Exception e)
{
throw e;
}
Note: Exception catches all the exceptions. That's why it is placed at the bottom.
You can simply do:
public String getResult() throws Exception {
String result = sample.getName(); // move this out of the try catch
try {
// some code
} catch (SomeOtherRunTimeException e) {
return null;
}
return result;
}
All other checked and unchecked exceptions will be propagated. There is no need to catch and rethrow.
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);
}
}