Exception on static variables - java

class A {
static int a = 1 / 0;
}
In this code when we load the class, it will throw an exception because of arithmetic exception. How can I catch that exception?

use this code.
static int a=0;
try{
a = 1/0;
}catch(Exception e){
e.printStackTrace();
}

using static block
public class A {
private static int a;
static {
try {
a = 1 / 0;
} catch (Exception e) {
System.out.print("error");
}
}
}

Make it in static block.
static {
try {
Integer a = 1 / 0;
} catch (Exception e) {
}
}

Related

Mockito to test the catch block of private method

I need to write a test to verify that when an IOException is thrown by the private method_C, Method_B returns True.
But
public final class A{
public static Boolean Method_B(){
try{
//call a private method C which throws IOException
Method_C
}
catch(final IOException e) {
return Boolean.True
}
}
private static Method_C() throws IOException {
return something;
}
What I tried:
#Test
public void testSomeExceptionOccured() throws IOException {
A Amock = mock(A.class);
doThrow(IOException.class).when(Amock.Method_C(any(),any(),any(),any()));
Boolean x = A.Method_B(some_inputs);
Assert.assertEquals(Boolean.TRUE, x);
}
I am getting compilation errors :
1.Cannot mock a final class
2. Method_C has private access in A
Any suggestions on how this can be rectified?
you are required to use finally in try catch
import java.io.*;
public class Test {
public static Boolean Method_B() {
try {
System.out.println("Main working going..");
File file = new File("./nofile.txt");
FileInputStream fis = new FileInputStream(file);
} catch (IOException e) {
// Exceptiona handling
System.out.println("No file found ");
} catch (Exception e) {
// Exceptiona handling
System.out.println(e);
} finally {
return true;
}
}
public static void main(String args[]) {
if (Test.Method_B()) {
System.out.println("Show true ans");
} else {
System.out.println("Sorry error occure");
}
}
}

Using a Exception's instance in catch clause

public class ExceptionObject {
public static void main(String[] args)
{
Exception exceptionObj = new Exception();
int a=1, b=0;
try
{
int c=a/b;
}
catch(exceptionObj)
{
exceptionObj.printStackTrace();
}
}
}
Why cant I use the "exceptionObj" which is an instance of the class Exception in catch clause.
Please advise, would be helpful.
You can try this:
int a = 1, b = 0;
try {
int c = a / b;
} catch (Exception exceptionObj) {
exceptionObj.printStackTrace();
}

threads synchronization issue

let's say i have 3 classes:
1. Storage which contains just one integer.
2. Counter which contains a thread inside who's responsible for counting (0,1,..,k) and stores each iteration of the loop index in Storage class.
3.Printer which contains a thread who's responsible for reading the value in class Storage and print it.
now i have to create a main class which creates these 3 objects runs the threads of Counter and Printer , and everynumber from(0,1,..,k) has to be printed just once and in the right order.
how do i synchronize the access to my Storage class so first i put a number inside Storage with Counter ,than print it with my Printer class ?
here's what i've wrote so far:
public class Storage {
private int num;
public Storage(){
}
public synchronized void setNum(int num){
this.num = num;
}
public synchronized int getNum(){
return num;
}
public class Counter implements Runnable {
Storage s;
public Counter(Storage t){
s = t;
}
#Override
public void run() {
int i = 0;
while(true){
s.setNum(i++);
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
public class Printer implements Runnable {
Storage s;
public Printer(Storage s){
this.s= s;
}
#Override
public void run() {
while(true){
System.out.println(s.getNum());
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
public class mainProg {
public static void main(String[] args){
Storage s = new Storage();
Counter c = new Counter(s);
Printer p = new Printer(s);
Thread c1 = new Thread(c);
Thread p2 = new Thread(p);
c1.start();
p2.start();
}
}
EDIT: i found out a solution, here it is:
public class Storage {
private int num;
private boolean available = false;
public Storage(){
}
public synchronized void setNum(int num){
while(available){
try {
wait();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
available = true;
notifyAll();
this.num = num;
}
public synchronized int getNum(){
while(!available){
try {
wait();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
available = false;
notifyAll();
return num;
}
}
This approach won't work, because it's not guaranteed that for every cycle of Counter a cycle of Printer will be executed in a parallel thread. You need to be able to store more than a one value in your Storage.
You can use BlockingQueue here and rewrite your Storage class like this:
public class Storage {
private BlockingQueue<Integer> numbers = new LinkedBlockingQueue<Integer>();
public void setNum(int num) {
try {
this.numbers.put(num);
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
}
public int getNum() {
try {
return numbers.take();
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
}
}
Note that if BlockingQueue is empty and Printer wants to get a new value, it will wait while a new element occurrs in the queue.

Generics and wildcard in Java for Futures Task

public class SOQuestion {
private class TaskResult1 {//some pojo
}
private class TaskResult2{// some other pojo
}
private class Task1 implements Callable<TaskResult1> {
public TaskResult1 call() throws InterruptedException {
// do something...
return new TaskResult1();
}
}
private class Task2 implements Callable<TaskResult2> {
public TaskResult2 call() throws InterruptedException {
// do something else...
return new TaskResult2();
}
}
private void cancelFuturesTask1(List<Future<TaskResult1>> futureList ){
for(Future<TaskResult1> future: futureList){
if(future.isDone())
{
continue;
} else
{
System.out.println("cancelling futures.....Task1.");
future.cancel(true);
}
}
}
private void cancelFuturesTask2(List<Future<TaskResult2>> futureList ){
for(Future<TaskResult2> future: futureList){
if(future.isDone())
{
continue;
} else
{
System.out.println("cancelling futures.....Task2.");
future.cancel(true);
}
}
}
void runTasks() {
ExecutorService executor = Executors.newFixedThreadPool(4);
CompletionService<TaskResult1> completionService1 = new ExecutorCompletionService<TaskResult1>(executor);
List<Future<TaskResult1>> futuresList1 = new ArrayList<Future<TaskResult1>>();
for (int i =0 ;i<10; i++) {
futuresList1.add(completionService1.submit(new Task1()));
}
for (int i = 0; i< 10; i++) {
try {
Future<TaskResult1> f = completionService1.take();
System.out.print(f.get());
System.out.println("....Completed..first one.. cancelling all others.");
cancelFuturesTask1(futuresList1);
} catch (InterruptedException e) {
System.out.println("Caught interrruption....");
break;
} catch (CancellationException e) {
System.out.println("Cancellation execution....");
break;
} catch (ExecutionException e) {
System.out.println("Execution exception....");
break;
}
}
CompletionService<TaskResult2> completionService2 = new ExecutorCompletionService<TaskResult2>(executor);
List<Future<TaskResult2>> futuresList2 = new ArrayList<Future<TaskResult2>>();
try{
for (int i =0 ;i<10; i++) {
futuresList2.add(completionService2.submit(new Task2()));
}
for (int i = 0; i< 10; i++) {
try {
Future<TaskResult2> f = completionService2.take();
System.out.print(f.get());
System.out.println("....Completed..first one.. cancelling all others.");
cancelFuturesTask2(futuresList2);
} catch (InterruptedException e) {
System.out.println("Caught interrruption....");
break;
} catch (CancellationException e) {
System.out.println("Cancellation execution....");
break;
} catch (ExecutionException e) {
System.out.println("Execution exception....");
break;
}
}
}catch(Exception e){
}
executor.shutdown();
}
}
As seen in the example, there is some repetition. I want to use Generics and wild card to generalize objects and re-use some methods.
My specific ask would be "cancelFuturesTask1" and "cancelFuturesTask2". Both methods do the same thing. How can I generalize them?
I read this: https://docs.oracle.com/javase/tutorial/java/generics/subtyping.html
I created a base class "TaskResult" extended "TaskResult1" and "TaskResult2"
private class TaskResult1 extends TaskResult
private class TaskResult2 extends TaskResult
and then use
List<Futures<? extends TaskResult>>
It gives me complication error and I am having some confusion in extending the concept to List<Futures<?>> in this case.
Any pointers or explanation on how to do that will help here.
Thanks in advance, let me know if you need some clarification.
This compiles fine for me, let me know if you get errors on it also.
public class FutureTest
{
public void cancelAll( Future<?> ... futures ) {
for( Future<?> f : futures ) {
if( !f.isDone() ) {
Logger.getLogger(FutureTest.class.getName()).log(
Level.INFO, "Canceling {0}", f);
f.cancel(true);
}
}
}
public <T extends Task1 & Task2> void cancelAll( List<Future<T>> futures ) {
cancelAll( futures.toArray( new Future[futures.size()]) );
}
}
interface Task1 {}
interface Task2 {}
For a more specific type, see my second method. You can do it with a Generic Method and Bounded Type Parameter, but only if all but one type are interfaces. Java doesn't support multiple inheritance, so you can't write one method that takes multiple (not covariant) class types. That's why I think unbounded (wildcard, "<?>") methods like the first example are better here.
https://docs.oracle.com/javase/tutorial/java/generics/boundedTypeParams.html

Java: Storing newInstance in a variable

I have been trying to store one of my classes(loaded using reflection) in an object using java.lang's newInstace() method. It seems to work within the method I create the newInstace() in, however outside it, the var throws a null pointer exception... Really makes no sense to me, does anyone know how to fix this?
Class:
public class ScriptManager {
public static Class currentScript;
public static Object ScriptInstance;
public static int State;
// 0 = Not Running
// 1 = Running
// 2 = Paused
public static void runScript() {
try {
ScriptInstance = currentScript.newInstance();
currentScript.getMethod("run").invoke(ScriptInstance);
State = 1;
MainFrame.onPause();
} catch (Exception e) {
e.printStackTrace();
}
}
public static void pauseScript() {
try {
currentScript.getMethod("pause").invoke(ScriptInstance);
State = 2;
MainFrame.onPause();
} catch (Exception e) {
e.printStackTrace();
}
}
public static void stopScript() {
try {
currentScript.getMethod("stop").invoke(ScriptInstance);
State = 0;
MainFrame.onStop();
} catch (Exception e) {
e.printStackTrace();
}
}
}
Error:
java.lang.NullPointerException
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
at java.lang.reflect.Method.invoke(Unknown Source)
at Bot.ScriptManager.pauseScript(ScriptManager.java:29)
Your use of static is messing you up. Try something like this:
public class ScriptManager {
private Class currentScript;
private Object scriptInstance;
private int state;
public ScriptManager() {
try {
scriptInstance = currentScript.newInstance();
currentScript.getMethod("run").invoke(scriptInstance);
//the rest
} catch (Exception e) {
e.printStackTrace();
}
}
public void pauseScript() {
try {
currentScript.getMethod("pause").invoke(scriptInstance);
//the rest
} catch (Exception e) {
e.printStackTrace();
}
}
//the rest
}
On a side note, use lower CamelCase for your variable names.
And keep your member variables private in this scenario.

Categories