Java Exercise 2 : Create a program for throw and throws





Exceptions are thrown with the help of the throw keyword. The throw keyword is used to indicate that an exception occurred.
throw is an object of any class that is derived from the Throwable class.


 The Syntax is 


throw throwableinstance //this is an instance of throwable






Example for throw statement


try
{
    
if< 0)
    
{
        
throw new NullPointerException();
    
}


}
catch(Exception e)
{
     
//statements
}





Example for throws statement


public class Example
{
    
public void exceptionExample()
    
{
        
try
        
{
            
// statements
            check
();
        
}
        
catch(Exception e)
        
{
            
//statements
        
}
    
}
    
// multiple exceptions separated by a comma

    
void check() throws NullPointerException,NegativeArraySizeException
    
{
        
if (< 0)
        
throw new NullPointerException();
        
if (< 0)
        
throw new NegativeArraySizeException();
    
}
}





Post a Comment

Copyright © Rough Record. Designed by OddThemes