Stackwalker within try-catch block java 9 - java

I am trying to print stack walker in exception block but it is displaying only current class
public class Test1 {
public void test() throws Exception{
Test2 test2 = new Test2();
test2.test();
}
}
public class Test2 {
public void test() throws Exception{
System.out.println(1/0);
}
}
public class TestStackWalker {
public static void main(String[] args) {
Test1 test1 = new Test1();
try {
test1.test();
} catch (Exception e) {
StackWalker stack = StackWalker.getInstance();
stack.forEach(System.out::println);
}
}
}

From StackWalker docs :
The walk method opens a sequential stream of StackFrames for the current thread and then applies the given function to walk the StackFrame stream.
Since you are calling it from your main method - there is only one StackFrame allocated and is being printed :
TestStackWalker.main(TestStackWalker.java:10)
If you want have access to each stack element of you exception's stack trace - use Throwable::getStackTrace which returns array of StackTraceElement :
class TestStackWalker {
public static void main(String[] args) {
Test1 test1 = new Test1();
try {
test1.test();
} catch (Exception e) {
Arrays.stream(e.getStackTrace()).forEach(System.out::println);
}
}
}
which will print :
Test2.test(Test2.java:3)
Test1.test(Test1.java:4)
TestStackWalker.main(TestStackWalker.java:7)
If you want only to print it Throwable::printStackTrace should be enough.

Related

Runtime Exec output

I want to execute a class method that is present in another file. I am doing the following:
import java.io.IOException;
public class run_java_program {
public static void main(String[] args) {
try {
Process process = Runtime.getRuntime().exec("java -cp C:\\Users\\96171\\eclipse-workspace\\IR_Project\\src test");
} catch (IOException e) {
e.printStackTrace();
}
}
}
But its not working. However on the cmd it is:
I tried replacing C:\\Users\\96171\\eclipse-workspace\\IR_Project\\src with C:/Users/96171/eclipse-workspace/IR_Project/src but still nothing is printed out to the console.
Here is the other program:
//import py4j.GatewayServer;
public class test {
public static void addNumbers(int a, int b) {
System.out.print(a + b);
}
// public static void addNumbers(int a, int b) {
// System.out.print(a + b);
// }
public static void main(String[] args) {
// GatewayServer gatewayServer = new GatewayServer(new test());
// gatewayServer.start();
// System.out.println("Gateway Server Started");
test t = new test();
t.addNumbers(5, 6);
}
}
The outputstream of the executed program test would become the inputstream for your current program run_java_program. Change your code to this and try:
import java.io.IOException;
public class run_java_program {
public static void main(String[] args) {
try {
Process process = Runtime.getRuntime().exec("java -cp C:\\Users\\96171\\eclipse-workspace\\IR_Project\\src test");
java.util.Scanner s = new java.util.Scanner(process.getInputStream());
System.out.println(s.nextLine());
} catch (IOException e) {
e.printStackTrace();
}
}
}
I used Scanner as I know it returns only one line. Based on your need you can also use apache common utils.

Which close() runs first?

If I have multiple resources, in a try catch, which one gets closed called on first?
public class TestRes {
public static void main(String[] args) {
TestRes tr = new TestRes();
tr.test();
}
public void test() {
try (MyResource1 r1 = new MyResource1(); MyResource2 r2 = new MyResource2(); ) {
System.out.print("T ");
} catch (IOException ioe) {
System.out.print("IOE ");
} finally {
System.out.print("F ");
}
}
class MyResource1 implements AutoCloseable {
public void close() throws IOException {
System.out.print("1 ");
}
}
class MyResource2 implements Closeable {
public void close() throws IOException {
throw new IOException();
}
}
}
This sample outputs:
T 1 IOE F
If I change the order so...
public class TestRes {
public static void main(String[] args) {
TestRes tr = new TestRes();
tr.test();
}
public void test() {
try (MyResource2 r2 = new MyResource2(); MyResource1 r1 = new MyResource1();) {
System.out.print("T ");
} catch (IOException ioe) {
System.out.print("IOE ");
} finally {
System.out.print("F ");
}
}
class MyResource1 implements AutoCloseable {
public void close() throws IOException {
System.out.print("1 ");
}
}
class MyResource2 implements Closeable {
public void close() throws IOException {
throw new IOException();
}
}
}
I get the same output - why?
It seems that you believe an exception from a close() method will prevent other close() methods from being called. That is wrong.
The Java Language Specification, section 14.20.3. try-with-resources, says:
Resources are closed in the reverse order from that in which they were initialized. A resource is closed only if it initialized to a non-null value. An exception from the closing of one resource does not prevent the closing of other resources. Such an exception is suppressed if an exception was thrown previously by an initializer, the try block, or the closing of a resource.
Which means that the close() method printing 1 will always be executed, and the first part answers your "Which close() runs first?" question.

Given the below code about Deadlock...why deadlock is not happening here and what changes should i make to occur the deadlock

public class Test15_DeadLockUsingJoinMethod {
public static void main(String[] args) throws InterruptedException {
JoinThread1 jt1=new JoinThread1(jt2);
JoinThread2 jt2=new JoinThread2(jt1);
jt1.start();
jt2.start();
}
}
class JoinThread1 extends Thread {
JoinThread2 jt2;
public JoinThread1(JoinThread2 jt2) {
this.jt2=jt2;
}
public void run() {
System.out.println("1st thread execution start");
try {
jt2.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("1st thread execution stopped");
}
}
class JoinThread2 extends Thread {
JoinThread1 jt1;
public JoinThread2(JoinThread1 jt1) {
this.jt1=jt1;
}
public void run() {
System.out.println("2nd thread execution start");
try {
jt1.join();
} catch (InterruptedException e){
e.printStackTrace();
}
System.out.println("2nd thread execution stopped");
}
}
Here I want to see the deadlock condition using only join() method. I know the deadlock code using synchronized keyword. But how can we execute deadlock condition using join method?
Your code doesn´t compile, you are using jt2 in the constructor of jt1, before it is defined.
In order to get a deadlock, you should define a new constructor for JoinThread1 that do not have any parameter. So, you first define jt1 using the new constructor. Then you define jt2 passing through parameter jt1 (like you have now). Then you should define a setter for the other thread in JoinThread1.
Example:
New constructor
public JoinThread1() {
}
Setter method
public void setThread(JoinThread2 jt2){
this.jt2 = jt2;
}
Main
public static void main(String[] args) throws InterruptedException {
JoinThread1 jt1=new JoinThread1();
JoinThread2 jt2=new JoinThread2(jt1);
jt1.setThread(jt2);
jt1.start();
jt2.start();
}
After that changes,you will get a deadlock.

How do I place my main method into a try catch block?

I'm making a game and my try and catch blocks work inside the methods, but one of the criteria for my assignment is to place the main method into a try catch block as well. But whenever I wrap my main method in a try{ } block, it gives me a compile error: Illegal start of type. I've looked this up and I've concluded I need to place the try block into its own method, but when I do this I get an Illegal start of expression. How exactly do I place my main method into a try catch block?
Main method:
public static void main(String[] args){
Board board = new Board();
board.display();
board.validate();
}
When I tried wrapping it in a try catch block (Illegal start type)
try{
public static void main(String[] args){
Board board = new Board();
board.display();
board.validate();
}
}
And when I tried to place it inside a method (Illegal start of expression)
public void tryCatch(){
try{
public static void main(String[] args){
Board board = new Board();
board.display();
board.validate();
}
}
}
You don't, you wrap the contents of your main method in the try-catch or have the main method re-throw the resulting exception
public static void main(String[] args){
try {
Board board = new Board();
board.display();
board.validate();
} catch (... exp) {
exp.printStackTrace();
}
}
Take a closer look at Catching and Handling Exceptions for more details
public static void main(String[] args) throws Exception {
Thread.currentThread().setUncaughtExceptionHandler(new Thread.UncaughtExceptionHandler() {
#Override
public void uncaughtException(Thread t, Throwable e) {
System.out.println("Caught Exception " + e);
}
});
throw new Exception("a serious problem occured");
}
and here is the output
Caught Exception java.lang.Exception: a serious problem occured

Custom Expcetion not throwing

The exception is never shown .
extended Exception class and override the method toString.and then called it.according to the condition it should display hahah , but it doesn't show anything..no errors either.
class Excp extends Exception {
public String toString() {
return "hahah";
}
}
public class exc {
boolean a = false;
void hey() throws Excp {
if (a)
throw new Excp();
}
public static void main(String... s) {
try {
new exc().hey();
} catch (Excp e) {
System.out.println(e);
}
}
}
Your condition
if(a)
will return false as you have intiialized a=false. Hence the if block will not execute the statement
throw new Excp();
Here
{
if(a)
throw new Excp();
}
A is false. Never goes in side the condition, because you haven't making true while initializing the object.
Try
try
{
Excp exc = new Excp();
exc.a= true;
exc.hey();
}
Side notes:
1)Please follow naming conventions.
2)Provide encapsulation.
3)Format your code always.
I think that you want to have a custom exception with your own error message, If so you can do like this
class MyException extends Exception{
MyException(String errorMsg){
super(errorMsg);
}
}
class Test{
public static void main(String[] args){
if(someCondition)
throw new MyException("My error message");
}
}

Categories

Resources