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

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

Related

Constructor in the Try/Catch block

The question is about the result of the below code. The answer is compilation error. However I really do not understand why we can't have constructor in try/catch block. I will put the the code below:
public class Test {
try {
public Test() {
System.out.println("GeeksforGeeks");
throw new Exception();
}
}
catch(Exception e) {
System.out.println("GFG");
}
public static void main(String [] args) {
Test test= new Test();
}
}
Because the assignments are statements and statements are allowed only inside blocks of code(methods, constructors, static initializers, etc.)
here's the clean code
public class Test {
public Test()throws Exception {
System.out.println("GeeksforGeeks");
throw new Exception();
}
public static void main(String [] args) {
try {
Test test= new Test();
} catch (Exception e) {
e.printStackTrace();
}
}
}
Because a constructor is a declaration, not a statement.
Your constructor can be called by other code, but merely declaring it does not execute it; that’s what new Test() does. Nothing is executed merely by declaring the constructor, so there is nothing that can throw an exception. Thus, there is nothing to catch.
In more general syntax terms, statements which don’t evaluate to a value can only exist in constructors, methods, and initialization blocks.
You can, however, do this:
public static void main(String[] args) {
try {
Test test = new Test();
} catch (Exception e) {
System.out.println(e);
}
}
new Test() actually executes the constructor, which is why it may throw an exception and thus you can legally attempt to catch any exception it may throw. Syntactically, all of the above code is inside a method (the main method), which is allowed.

Stackwalker within try-catch block java 9

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.

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.

Understanding the Try Catch block behavior

I ran into a strange problem with try catch which got me doubting about my own realization of exception handling fundamentals. As per the basic syntax
try{
code to be checked
}
catch(Exception e){}
finally{}
However the code below gives me a null pointer exception which I believe should have been caught.
class Ideone
{
public static void main (String[] args) throws java.lang.Exception
{
try{
for(Model m: Null Collection coming from DB)
System.out.println("Inner Block");
System.out.println("Outer Block");
}catch(Exception e){}
}
}
The following snippet prints "An exception!"
List<String> strings = null;
try {
for (String s : strings) {
System.out.println(s);
}
} catch (Exception e) {
System.out.println("An exception!");
}
And as others have pointed out, and you stated yourself, Runtime exceptions are caugth by Exception catches
Have you tried recompiling all your code from scratch? In my team (250.000 lines codebase) using eclipse we sometimes have trouble with bad compiles that can give unexplainable problemes like this. We usually solve them by a complete recompile.
Are you sure about your issue? I believe there's some clean-up code in your catch which hasn't been initialized yet - hence the exception. Would help if you post your actual code.
The following works as expected:
import java.util.List;
public class Main {
public static void main(String[] args) {
List i=null;
try{
for(Object o: i) {
System.out.println("Inner Block");
}
System.out.println("Outer Block");
}catch(Exception e){}
}
}
Understanding the Try Catch block behavior?
The main reason to use try-catch block is to handle something will goes wrong with your code or something you are unexpected for the normal case and something will throw an exception somehow and to handle it in catch block, and the finally block is used almost to close any opened stream and it will run every time in the code even if the try or catch returned any value (except for system termination).
In your code it seems that there is something you get it from database which is null or not initialized yet or it is already returned from database of null value, Now you cannot use null object if it's not initialized already! you have to insure if it's null or not then use it like this:
class Ideone {
public static void main(String[] args) throws java.lang.Exception {
try {
if(Null Collection coming from DB != null){
for(Model m: Null Collection coming from DB)
System.out.println("Inner Block");
}
System.out.println("Outer Block");
} catch (Exception e) {}
}
}
The NullPointerException is extends RuntimeException and it's thrown when you try to use a null object.
i has not been initialized,
public class Ideone{
public static void main (String[] args) throws java.lang.Exception
{
int i = 0;
try{
if(i<2)
System.out.println("Inner Block");
System.out.println("Outer Block");
}catch(Exception e){}
}
}
Cannot reproduce.
I tried this
public static void main (String[] args) throws java.lang.Exception
{
Collection c = null ;
try{
for(Object i:c)
System.out.println("Inner Block");
System.out.println("Outer Block");
}catch(Exception e){}
}
It works well.

Java exceptions and program flow: how to know if the program will stop or continue after an exception is thrown?

Check this code:
public class Tests {
public static Boolean test() {
throw new RuntimeException();
}
public static void main(String[] args) {
Boolean b = test();
System.out.println("boolean = " + b);
}
}
Why the System.out.println() line is not executed?
It isn't executed because uncaught exceptions terminate the current thread(main thread in your case).
test() throws a RuntimeException. Surrounding test() with a try-catch would catch the exception and allow your program to continue.
try {
test();
} catch(RuntimeException e) {
System.out.println("test() failed");
}
Exceptions "bubble up" to the "highest" level exception handler.
In this case, it's the JVM itself with the exception handler, since you define none.
The JVM will halt program execution since it doesn't know what else to do with the uncaught exception.
You are calling the test() method which throws exception. The program will stop executing as soon as exception is thrown and not handled. You need to handle exception by putting it in try-catch block
public static Boolean test() {
try{
throw new RuntimeException();
}catch(RuntimeException e){
e.printStackTrace();
}
return true;
}
public static void main(String[] args) {
Boolean b = test();
System.out.println("boolean = " + b);
}
}
or you can declare the method to throw exception and handle it in the main method
public static Boolean test() throws RuntimeException {
throw new RuntimeException();
}
public static void main(String[] args) {
Boolean b = false;
try{
b = test();
}catch(Exception e){
e.printStackTrace();
}
System.out.println("boolean = " + b);
}
If an exception is thrown in try block, all the statements below it won't be executed and then catch block is executed.
If there is no catch block, then finally block is executed.
Finally block will be executed all the times if JVM does not shut down.

Categories

Resources