Invorking fillInStackTrace method after invoked printStackTrace method - java

Blow is a example copied from Think in Java 4 edition
public class Rethrowing {
public static void f() throws Exception {
System.out.println("originating the exception in f()");
throw new Exception("thrown from f()");
}
public static void h() throws Exception {
try {
f();
} catch (Exception e) {
System.out.println("Inside h(),e.printStackTrace()");
e.printStackTrace(System.out); //first print line throw (Exception) e.fillInStackTrace();
}
}
public static void main(String[] args) {
try {
h();
} catch (Exception e) {
System.out.println("main: printStackTrace()");
e.printStackTrace(System.out);
}
}
}
Output:
originating the exception in f()
Inside h(),e.printStackTrace()
java.lang.Exception: thrown from f()
at Rethrowing.f(Rethrowing.java:20)
at Rethrowing.h(Rethrowing.java:25)
at Rethrowing.main(Rethrowing.java:35)
main: printStackTrace()
java.lang.Exception: thrown from f()
at Rethrowing.f(Rethrowing.java:20)
at Rethrowing.h(Rethrowing.java:25)
at Rethrowing.main(Rethrowing.java:35)
When comment //first print line
Output:
originating the exception in f()
Inside h(),e.printStackTrace()
main: printStackTrace()
java.lang.Exception: thrown from f()
at Rethrowing.h(Rethrowing.java:29)
at Rethrowing.main(Rethrowing.java:35)
My question is why i first invoke e.printStackTrace(printOut out ) method before the fillInStackTrace mehod, and then the fillInStackTrace seems not available. Any one can do me a faver, thanks in advance.

user917879, When you call e.fillInStackTrace(); it resets the StackTrace. So, to print the current StackTrace - before it is get reset - you need to invoke the e.printStackTrace(printOut out ) first.

Related

tips "Unhandled exception type xxx" in eclipse

I don't think I understand the try-catch block and throws really.
public class TestException {
public static void main(String[] args) {
new TestException().tt();
}
public void tt() {
try {
throw new RuntimeException();
}catch (Exception e) {
throw e;
}
}
}
When in Eclipse, there is an error hint about 'Unhandled exception type xxx', and if you run this, you will get an
Exception in thread "main" java.lang.Error: Unresolved compilation problem:
Unhandled exception type Exception
But in Idea, there's no errors. It runs and throws the exception correctly.
In my opnion, the 'e' was not declared as a RuntimeException(althrough it is an RuntimeException), so the tt() method must be declared with throws. But actually it's not. Why?
This should answer your question:
public class TestException {
public static void main(String[] args) {
new TestException().tt();
}
public void tt() {
try {
throw new RuntimeException();
}catch (Exception e) {
throw new RuntimeException(e);
}
}
}
If you use throws, you tell those who use your function, "My function may throw exceptions. You have to handle that."
You should get difference of throws and throw in this sentence.
If you use try-catch, you handle that exception.
1) You should add throws keyword like below
public class TestException {
public static void main(String[] args) {
new TestException().tt();
}
public void tt() **throws Exception** {
try {
throw new RuntimeException();
}catch (Exception e) {
throw e;
}
}
}
2) Handle exception where you use function
public class TestException {
public static void main(String[] args) {
try{
new TestException().tt();
}catch(Exception e){
System.out.println("Error handled");
}
}
public void tt() throws Exception {
try {
throw new RuntimeException();
}catch (Exception e) {
throw e;
}
}
}
In general if you catch an exception you handle it. Like this
public class TestException {
public static void main(String[] args) {
new TestException().tt();
}
public void tt() {
try {
throw new RuntimeException();
}catch (Exception e) {
System.out.println("Error caught! ")
}
}
}
or
public class TestException {
public static void main(String[] args) {
try {
new TestException().tt();
}catch(Exception e){
System.out.println("Error caught! ")
}
}
public void tt() throws RuntimeException {
throw new RuntimeException();
}
}
You can also throw other's exception
public class TestException {
public static void main(String[] args) {
try{
new TestException().a();
}catch(Exception e){
System.out.println("Error handled");
}
}
public void a() throws Exception {
b();
}
public void b() throws Exception {
c();
}
public void c() throws Exception {
throw new RuntimeException();
}
}
I think that you want to look into 'Checked Exceptions' and 'Unchecked Exceptions'.
Only Checked Exceptions need to be declared in a methods signature, and RuntimeException is an unchecked exception (though you can declare it if you like - it just isn't necessary to compile).
https://docs.oracle.com/javase/7/docs/api/java/lang/Exception.html
The API for java Exception says:
"The class Exception and any subclasses that are not also subclasses of RuntimeException are checked exceptions. Checked exceptions need to be declared in a method or constructor's throws clause if they can be thrown by the execution of the method or constructor and propagate outside the method or constructor boundary"
https://docs.oracle.com/javase/7/docs/api/java/lang/RuntimeException.html
The API for java RuntimeException says:
"RuntimeException and its subclasses are unchecked exceptions. Unchecked exceptions do not need to be declared in a method or constructor's throws clause if they can be thrown by the execution of the method or constructor and propagate outside the method or constructor boundary."
In my opnion, the 'e' was not declared as a RuntimeException(althrough it is an RuntimeException), so the tt() method must be declared with throws. But actually it's not. Why?
Let's consider what we know:
When using rethrow syntax, the existing exception object (e) is rethrown.
e is an object of class Exception, or one of its subtypes.
RuntimeException is a subtype of exception, and is not compiled time checked, so it's possible the re-thrown object is a non compile time checked object.
The compiler cannot see a place where the code definitely, or even possibly throws a compile checked exception, and so it makes sense that it does not force those semantics.
For example, if you change your catch to an IOException, the compiler will not allow you to do that without a line in the try which could possibly lead to an IOException.
If you added such a line, then the compiler would recognize that the throw would rethrow a compile time checked exception, and make you catch it again, or mark the function with the appropriate throws clause.
As for eclipse, your code compiles OK in mine with my JDK.

java.lang.NullPointerException and return code

I'm running some java binary from bash like:
run_me.sh
$JAVA_HOME/bin/java -Djava.library.path=path1/libs/opencv/lib -jar path2/bin/application.jar
echo "Exit code: "$?
but inside application I get java.lang.NullPointerException, howewer return code is 0, but I need some non zero exit code to understand from bash that application failed.
What is the proper way to handle such cases?
Update:
Here is an exxample of 'nested' try catch blocks, when I throw exception in inner_package_class return code is 0. So what is the proper way to get exception from inner_package_class.method1()?
public static void main(String[] args) {
try {
inner_package_class.method1();
System.out.printf("After inner method!\n");
} catch (Throwable t) {
System.exit(1);
}
}
public class inner_package_class {
public static void method1() {
System.out.printf("From inner method!\n");
try
{
throw new Exception("Some exception 2.");
} catch (Throwable t) {
}
}
}
Update 1:
This work as expected (return non zero exit code).
public class inner_package_class {
public static void method1() throws Exception {
System.out.printf("From inner method!\n");
throw new Exception("Some exception 2.");
}
}
You can add a try-catch-block around your main method and use
System.exit(1)
when you catch a Throwable
public static void main(String[] args) {
try {
... // your original code
} catch (Throwable t) {
// log the exception
t.printStacktrace(); // or use your logging framework
System.exit(1);
}
}
the return code is set by the exit method of System: by the way if, for instance, You want to return -1 in case of exception you can do as follow: in Your Main class you have to catch all throwable (so you will handle all possible case). here is an example
public static void main(String[] args) {
try { YOUR CODE
} catch(throwable t){
System.exit(-1);
}
System.exit(0);
}
the code show You how return -1 in case of exception and 0 in case of success.

exception-handling method exit without finishing

I am learning about exception handling and now I have a question.
I think the result of this code is 345,however,I don't know why the result is 35.
Shouldn't it run the code System.out.println(4) even though there is an exception happened?
public class Six {
public static void main(String[] args) {
try {
method1();
} catch(Exception e) {
System.out.println(5);
}
}
static void method1() {
try {
method2();
System.out.println(1);
} catch(ArithmeticException e) {
System.out.println(2);
} finally {
System.out.println(3);
}
System.out.println(4);
}
static void method2() {
throw new NullPointerException();
}
}
In method2() a NullPointerException is thrown whereas in method1() you only catch ArithmethicException which is a different Exception. In this case the the catch block of method1() is not processed. Only the finally block will be executed and then the method exits and the exception is re-thrown to the calling method (main())
No, 4 is not printed because the NullPointerException is still active, it was not caught at that point. The finally block (where 3 is printed) is guaranteed to be executed so you can do cleanup there, but it does not 'stop' the exception.

Handling exceptions in JAVA

I know that if we have a normal code without try and catch statements,then if an exception occurs,then the default exception handler of JVM handles that exception.
I have a code...
public class St
{
public static void main(String args[])
{
try
{
int y=23/0;
}
catch(Exception e)
{
System.out.println("Division by zero");
}
}
}
As far as I know, in this code exception occurs at line 7,an object of class Exception is thrown and that's why we have taken as argument an object of class Exception in order to catch the exception.Am I right upto now????
But why this code shows a compile time error...
public class St
{
public static void main(String args[])
{
Exception e=new Exception();
try
{
int y=23/0;
}
catch(e)
{
System.out.println("Division by zero");
}
}
}
In this I have created an object reference e of class Exception,and that I have taken as argument in catch.But its not running,giving error at compile time.Can someone explain why???
That's just not how the catch block works. It requires an ExceptionType argument and then a name to reference the exception once it's been caught. It doesn't take an object as an argument, but the name of a class that inherits from 'Throwable'.

Java exception specification for the main method

Do we not need exception specification for the main method in a Java program. For example, the following code works exactly the same without specifying "throws Xcept" for the main method.
class Xcept extends Exception {
public Xcept(){
}
public Xcept(String msg){
super(msg);
}
}
public class MyException {
public void f() throws Xcept {
System.out.println("Exception from f()");
throw new Xcept("Simple Exception");
}
public static void main(String[] args) throws Xcept {
MyException sed = new MyException();
try {
sed.f();
} catch(Xcept e) {
e.printStackTrace();
}
finally {
System.out.println("Reached here");
}
}
}
I read that java enforces this, but I don't get a compile time error if I exclude this specification for the main method.
That's because Xcept will never be thrown out of your main method, as you actually catch it there... The sed.f() call may result in an Xcept being thrown, but it's caught and handled.

Categories