i was trying to run the following code but i am getting error please clarify my doubt
import java.util.*;
class Except
{ public class AlfaException extends Exception{}
public static void main(String[] args)
{
int b;
Scanner s=new Scanner(System.in);
try
{
b=s.nextInt();
}
catch(InputMismatchException ex)
{
try
{
if(('b'> 67)&&('b'<83)){}
}
catch(AlfaException e){
throw new AlfaException("hello");
}
System.out.println("error found");
}
}
}
Except.java:20: non-static variable this cannot be referenced from a static cont
ext
throw new AlfaException("hello");
^
1 error
Static context is a context that runs on class without actual instance of that class. Your main method is static, that means it can only access static variables. However, your AlfaException is not static. Meaning that it will be bound to an instance of
Exceptclass – which you do not have.Therefore you have 2 choises:
public static class AlfaException extends Exception{}. That will make it reside in static scope so it will be possible to access it from static functions.main(...)method logic into non-static context. Create a function calleddoWork()that is not static, move all the code frommaintodoWork, and then call it like this:.