Since your main() method and your ratio() use scanners, they throw exceptions when an exception occurs, the normal program flow is interrupted, and the program / application is interrupted abnormally, which is not recommended, therefore, these exceptions are handled. An exception can occur for various reasons, the following are some scenarios in which an exception occurs.
A user has entered invalid data. A file that needs to be opened cannot be found. A network connection has been lost in the middle of communications or the JVM has run out of memory.
You can handle these exceptions using Try / Catch blocks, or you can handle them with the word throws after defining a method, in your case these two approaches would be:
With Try / Catch :
public static void main() { try{ Scanner sc=new Scanner(System.in); int T=sc.nextInt();// number of test cases sc.close(); } catch(NoSuchElementException e){ System.out.print("Exception handled" + e); //rest of method } static void ratio(){ try{ Scanner sc1=new Scanner(System.in); int N=sc1.nextInt();} catch(NoSuchElementException e){ System.out.print("Exception handled" + e);} //rest of method }
With "throws":
public static void main()throws Exception{
source share