order of execution of static method - java

public class Sample {
public void method()
{
System.out.println("normal hai");
}
public static void method1()
{
System.out.println("static hai");
}
public static void main(String[] args) {
Sample s = null;
s.method1();
s.method();
}
}
and the output is:
Exception in thread "main" java.lang.NullPointerException
at com.csvfile.sample.main(Sample.java:22)
static hai
Why has the order changed? It should output:
static hai
Exception in thread "main" java.lang.NullPointerException
at com.csvfile.sample1.main(Sample.java:22)

The issue you have is that the Exception is printed to System.err while your code prints to System.out.
So, without a badly named class (PascalCase please) we can do:
public static void main(String[] args) throws Exception {
final System system = null;
system.out.println("Odd");
System.out.println(system.toString());
}
And the output I get is:
Exception in thread "main" java.lang.NullPointerException
Odd
at com.boris.testbench.App.main(App.java:14)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:497)
at com.intellij.rt.execution.application.AppMain.main(AppMain.java:140)
So they're actually interleaved. i.e. the order of the output is undefined as there are two output streams being printed to the console.
Changing the code to:
public static void main(String[] args) throws Exception {
final System system = null;
system.err.println("Odd");
System.err.println(system.toString());
}
Produces the desired result.
You could also catch the exception and print it to System.out to achieve the same effect:
public static void main(String[] args) throws Exception {
final System system = null;
system.out.println("Odd");
try {
System.out.println(system.toString());
} catch (RuntimeException ex) {
ex.printStackTrace(System.out);
}
}
P.S. I'm sure you know this, but you should never call a static method on an instance of the class. You should always call the static method on the class itself. So in your example, you should always do:
public static void main(String[] args) {
sample1 s = new sample1();
s=null;
sample1.method1();
s.method();
}

That is because the exception is printed to STDERR and System.out.println() is printed to STDOUT and both streams are not synchronized.
If you call it a second time the order can change.

This is because out and err are two different output streams. However, both of them print on console. So you do not see them as different streams. Try the below code and check output.
for (int i = 0; i < 10; i++) {
System.out.println(i);
System.err.println(i);
}

Just a good to know thing in Java:
In Java there are several types of init fileds:
let`s see an example:
public class HunarianEngineer{
static{
System.out.println("1.This is a static block, called when the JVM pull in the class first time ever");
}
{
System.out.println("2.This is an instance block, runs before constructor");
}
public HungarianEngineer(){
System.out.println("3.I`m a constructor");
}
}//EndOfClass
Read more about them:
https://docs.oracle.com/javase/tutorial/java/javaOO/initial.html
or here:
http://www.thejavageek.com/2013/07/21/initialization-blocks-constructors-and-their-order-of-execution/

Related

Java throw keyword

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.

Open Task manager and handle its multiple tabs using Java code

I want to open Task Manager and click on its tabs like 'Process','Performance','App history', etc. by using core java only.
Tried to begin with
public class Desktop1 {
public static void main(String[] args) throws IOException {
Runtime.getRuntime().exec(System.getenv("windir") +"\\system32\\"+"Taskmgr.exe");
}
}
Exception in thread "main" java.io.IOException: Cannot run program "C:\WINDOWS\system32\Taskmgr.exe": CreateProcess error=740, The requested operation requires elevation
There are multiple ways of achieving this. The simplest way is mentioned by #mkane in his comment. Programatically, this could be achieved in the following way:
Add following dependency to your application:
<dependency>
<groupId>com.vnetpublishing.java</groupId>
<artifactId>super-user-application</artifactId>
<version>0.0.5</version>
</dependency>
Now you can make your class extend SuperUserApplication class and override its run() as:
public int run(String[] strings) {
try {
Runtime.getRuntime().exec(System.getenv("windir") +"\\system32\\"+"Taskmgr.exe");
} catch (IOException e) {
e.printStackTrace();
}
return 0;
}
Now call static run(...) of class SU passing in the instance of the class extending SuperUserApplication. Here is a complete example for your reference:
public class Main extends SuperUserApplication {
public static void main(String[] args) {
SU.run(new Main(), args);
}
// #Override
public int run(String[] strings) {
try {
Runtime.getRuntime().exec(System.getenv("windir") +"\\system32\\"+"Taskmgr.exe");
} catch (IOException e) {
e.printStackTrace();
}
return 0;
}
}

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.

Error: unreported exception java.io.FileNotFoundException; must be caught or declared to be thrown[7]

I keep getting the FileNotFoundException, even though I´m throwing it.
Here´s the code:
import java.util.*;
import java.io.*;
public class kt_6_2 {
public static void main(String[] args) {
File file = new File("magicSquare.txt");
fileRead(file);
}
static void fileRead (File dummyFile) throws FileNotFoundException {
Scanner scanner = new Scanner(dummyFile);
String[] squareLines = new String[3];
for (int a = 0; a < 3; a++) {
squareLines[a] = scanner.nextLine();
scanner.nextLine();
}
System.out.println(squareLines[2]);
}
}
edit: the error message is:
kt_6_2.java:7: error: unreported exception FileNotFoundException; must be caught
or declared to be thrown
fileRead(file);
^
1 error
Since your main method is calling your fileRead() method. And instead of handling exception your fileRead() method has decided to throw the Exception.
So in exception scenario, once its thrown from fileRead() method it should be caught in your main() method. However, your main() can further throw this exception.
you need to write as
public static void main(String[] args) throws FileNotFoundException {
....
or if you want to handle the exception, you should write as:
public static void main(String[] args) {
File file = new File("magicSquare.txt");
try{
fileRead(file);
} catch (FileNotFoundException ex) {
//exception handling code
}
}
must be caught or declared to be thrown
What exactly do you not understand here?
You use a method fileRead that can throw FileNotFoundException, hence you must either catch it, or hand it upwards, so your main method would need a throws clause.
But the latter choice is, of course, a bad one. So simply wrap that readFile invokation in a try/catch block.

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