Java throw keyword - java

public class MyThrow {
public static void main(String[] args) {
System.out.println(2/0);
throw new ArithmeticException("please be carefull");
}
}
Why is the custom exception not showing?
It is showing the default one.

For Exception handling we would use a try catch statement like
try {
System.out.println(2/0);
}catch(ArithmeticException e) {
System.out.println("Please Be Careful");
}
In your case the Custom Exception is not showing up since in the previous line you have a AthmeticExcpetion hence that exception will be thrown and Java will stop and not execute you exception.

Related

Determining which method throws exception

Below code catches an IOException , the first exception throw will be the one that is caught. To determine which method is throwing the IOException is the sole solution to wrap each method that throws an IOException in a try catch block ? I ask as my planned solution adds alot of try catch code and perhaps there is a cleaner solution to determine which method is throwing IOException ?
import java.io.IOException;
import java.net.SocketException;
public class Driver {
private static void te() throws IOException {
throw new java.net.SocketException("Connection Reset");
}
private static void te2() throws IOException {
throw new java.net.SocketException("Connection Reset 2");
}
private static void te3() throws IOException {
throw new java.net.SocketException("Connection Reset 3");
}
public static void main(String args[]) {
try {
Driver.te();
Driver.te2();
Driver.te3();
} catch (IOException e) {
e.printStackTrace();
}
}
}
The answer depends on your required logic. If the treatment of your exception is supposed to be different depending on which method threw the exception, (meaning that within catch you will need to write different error handling code depending on which method threw the exception, then you do need to wrap each method invocation into separate try-catch. But if the error handling is the same then your code is fine (except that usually, you print your stacktrace into a log file) and you would be able to figure out which method threw the exception by reading your stacktrace as a human user. But then again if the error handling is the same then your code doesn't need to know which specific method threw the exception.
I don't know why you are doing something like that, and surely a real situation would be far away from this code fragment but, in "real life" I would consider extending IOException: so you will have a single try with three catches in the main method. Do you like this solution?
Create a custom exception for each method:
class TeException extends IOException { /* constructor */ }
private static void te() throws TeException {
throw new java.net.SocketException("Connection Reset");
}
Then it is fairly easy to distinguish among multiple exception with separate catch blocks:
try {
Driver.te();
Driver.te2();
Driver.te3();
} catch (TeException e) {
e.printStackTrace();
} catch (Te2Exception e) {
e.printStackTrace();
} catch (Te3Exception e) {
e.printStackTrace();
}
An alternative might be to read the method that failed with the stacktrace:
final String failedMethodName = e.getStackTrace()[0].getMethodName());
You can do it as follows:
try {
Main.te();
Main.te2();
Main.te3();
} catch (Exception e) {
System.out.println(e.getStackTrace()[0].getMethodName());
}
In a real life scenario, you would probably be writing something to a log file in the case of an exception. For example:
public class Driver {
// assuming slf4j
private static Logger logger = LoggerFactory.getLogger(Driver.class);
private static void te() throws IOException {
logger.error("exception happened in te()");
throw new java.net.SocketException("Connection Reset");
}
}
Then, to figure out which methods threw exceptions, you would only need to open the log file and check.

Throwing Exceptions from Exception class in java

Ok ... So I am learning about exceptions in java and i am currently at throw statements. I throw an exception of Exception class, and then re-throw it from the catch block again to handle it in the main function. But whenever i throw it as Exception class, i always get an Error in the catch block(where i re-throw it to be handled in main).But as soon as i change the thrown and caught Exceptions to some particular Exceptions like NullPointerException, it works!
Error Code:
class ThrowingExceptions {
static boolean enable3dRendering = false;
public static void main(String [] com) {
try {
renderWorld();
}
catch(Exception e) {
System.out.println("Rendering in 2d.");
}
}
static void renderWorld() {
try{
if(!enable3dRendering) {
System.out.println("3d rendering is disabled. Enable 3d mode to render.");
throw new Exception("3d mode Disabled.");
}
else {
System.out.println("The World is Empty!");
}
}
catch(Exception e) {
System.out.println("Please handle the error");
throw e; // It gives me an error here
}
}
}
Working Code:
class ThrowingExceptions {
static boolean enable3dRendering = false;
public static void main(String [] com) {
try {
renderWorld();
}
catch(NullPointerException e) {
System.out.println("Rendering in 2d.");
}
}
static void renderWorld() {
try{
if(!enable3dRendering) {
System.out.println("3d rendering is disabled. Enable 3d mode to render.");
throw new NullPointerException("3d mode Disabled.");
}
else {
System.out.println("The World is Empty!");
}
}
catch(NullPointerException e) {
System.out.println("Please handle the error");
throw e;
}
}
}
Why doesn't it work with Exception class and worked with its subclass??
Note :- The error i get in the error code is Unhandled exception type Exception
Runtime exceptions extend RuntimeException. They don’t have to be handled or declared.
They can be thrown by the programmer or by the JVM.
Checked exceptions have Exception in their hierarchy but not RuntimeException. They
must be handled or declared. They can be thrown by the programmer or by the JVM.
Errors extend the Error class. They are thrown by the JVM and should not be handled or
declared.
When method throws checked exception (1) you should handle or rethow it.
When method throws uncheked exception (2) you can handle or rethrow it, but it's not obligatory.
But whenever i throw it as Exception class, i always get an Error in
the catch block(where i re-throw it to be handled in main)
It means that your method is throwing checked exception which should be handled or rethrowed.
Handling:
public class Main {
public static void main(String[] args) {
try {
throw new Exception();
} catch (Exception e) {
try {
throw new Exception();
} catch (Exception e1) {
e1.printStackTrace();
}
}
}
}
Rethrowing:
public class Main {
public static void main(String[] args) throws Exception {
try {
throw new Exception();
} catch (Exception e) {
throw new Exception();
}
}
}
In your case:
// You declaring that the caller should handle exception
static void renderWorld() throws Exception {
try {
if(!enable3dRendering) {
System.out.println("3d rendering is disabled. Enable 3d mode to render.");
throw new Exception("3d mode Disabled.");
} else {
System.out.println("The World is Empty!");
}
} catch(Exception e) {
System.out.println("Please handle the error");
// You cannot just throw uncheked exception here
// You should handle it yourself or a caller should do it
throw e;
}
}
Changing
static void renderWorld() { ... }
to
static void renderWorld() throws Exception { ... }
should fix this. This is for the reason that runtime exception are unchecked exceptions.
Would recommend you to read about the Checked and Unchecked exception in details here - Java: checked vs unchecked exception explanation.
It's because they are several Exception classes which are inherited from the class Exception. Each can be throwed, catched but they divide into two groups:
Checked and unchecked exceptions:
An unchecked exception doesn't need to be handled and the
NullPointerException which you tried is from that group, so you don't need to care about it technically.
A checked exception need to be handled every time or it won't
compile, these exceptions are like IOException.
Since the base Exception Object can be checked and unchecked as well the compiler cares about that it should be handled everytime.
If you give it a try and change the NullPointerException to IOException it won't compile either cause it is a Checked Exception. So it was just random, that you exactly find one type of Exception which your code can be work without compile error.
For more info visit my blog post about it:
http://www.zoltanraffai.com/blog/?p=93

Catching an Exception from a called Method

This is something that's been bugging me for a while with regards to Program Flow.
I wanted to know if it's possible to catch an error from a Method in order to stop it from executing the Method that would normally follow it like the example bellow that I can't get to work.
public class MyClass {
public static void main(String[] args) {
// this method catches an exception and stops running
method01();
// this method will continue anyway which I don't want
method02();
};
};
I would normally have a static int variable that will initialize as 0 when the program is run and then if a method ever catches an exception it will increment that int and each method will only run if the int is 0.
This works but I was just wondering if I could replace the int shindig with exception handling.
Can you try:
try {
method01()
} catch (final Exception e) {
// do something
return; ///stop processing exit
}
the method01 will throw Exception:
private void method01() throws Exception {
// something
}
If you only want to terminate the whole program in case of an exception you just need to throw a RuntimeException without any further declaration. There are also specialized sub classes for explicit types of exceptions, like NullPointerException or IllegalStateException. See the "Direct Known Subclasses" section in the JavaDoc.
public class MyClass {
public static void main(String[] args) {
method01();
method02(); //method02 won't be called in case of an exception
}
private static void method01() {
// ...
if (true) // something goes wrong
throw new RuntimeException();
// further code won't be executed in case of an exception
}
private static void method02() {
System.out.println("method02 called");
}
}
Optionally it is possible to handle the exception with a try-catch-block:
public static void main(String[] args) {
try {
method01();
method02(); // method02 won't be called in case of an exception
} catch (Exception e) {
System.err.println("something went wrong");
}
}
// other code keeps unchanged...
If you want to enforce exception handling, you have to throw a subclass of Exception that is not derived from RuntimeException. But those exceptions have to be declared within the method Signature.
private static void method01() throws IOException {
throw new IOException();
}
You put method01 and method02 in to same try block:
public class MyClass {
public static void main(String[] args) {
try {
// This method catches an exception and stops running.
method01();
// This method will not continue if method01 have exception.
method02();
} catch (Exception e) {
e.printStackTrace();
}
}
// declare method01, method02, others...
}
Notice: You have mistakes at the end of code block ( }; }; )
Depends on what your method really does.
If your program should continue working also when an exception arise (e.g. NumberFormatException when parsing an input or in general a checked exception) a lot of people will suggest you to not use exception for flow control, but IMHO in very well defined cases (like NumberFormatException) the flow CAN be controlled by try catch statements and exceptions, it's really up to you.
A way to do so is to use the method returned parameter (also #Nikola answer works in this way, the point is to use the catch part of a try catch as flow control):
public class MyClass {
public static void main(String[] args) {
if(method01()) method02();
};
};
public boolean method01(){
try{
//some business
}catch(MyCheckedException e){
e.printStackTrace();
return false;
}
return true;
}
NB: You should use this approach only in well defined situations! If a file CAN be absent in a directory while opening it (checked FileNotFoundException), you COULD use this approach. If the file SHOULD be there and its not, the exception MUST stop the program.

What if a method generates a checked exception and handle it itself?

class Xyz {
public static void yolo() {
try {
throw new IllegalAccessException("demo");
} catch (IllegalAccessException e) {
System.out.println("lol");
}
}
public static void main(String args[]) {
Xyz.yolo();
}
}
Since there is no exception that is going out of the yolo method, I don't need to write "yolo() throws IllegalAccessException". Right?
You are correct. You only need to declare unhandled checked exceptions.
Exactly. A method only needs to declare throws for exceptions which leave it and aren't handled by itself.
Perfect!
If you will use throws keyword for handing Exception then this method will not handle the exception rather then main() will handle this exception at time of calling this method.

Why i can`t throw Exception(checked) in a method that is invoked in a try catch statement?

public class simple {
public static void main(String[] args) {
try {
System.out.print("hello ");
throwit();
} catch (Exception re) {
System.out.print("caught ");
}
}
public static void throwit(){ // line number 11
throw new Exception(); // line number 12
}
}
why does it give me a compile error in line number 12.
If i use throws Exception for line number 11 then it work fine.
If i throw subclass of Exception(in line number 12) then it work properly... why so?...
I want to know actually what happen in back side(how does compiler shows error for this)?
You have a method there which is throwing a checked exception, but its method signature doesn't specify that it is able to do that. All checked exceptions have to be declared in the method signature, and explicitly handled by try/catch blocks or by rethrowing; that's what the definition of a checked exception is. :)
This line:
public static void throwit()
should be
public static void throwit() throws Exception

Categories

Resources