java.lang.NullPointerException in UDF in PIG - exception

my UDF converts the given input to UPPER case
package myudfs;
import java.io.IOException;
import org.apache.pig.EvalFunc;
import org.apache.pig.data.Tuple;
public class UPPER extends EvalFunc<String>
{
public String exec(Tuple input) throws IOException{
if(input==null|| input.size()==0)
return null;
try{
String str=(String)input.get(0);
return str.toUpperCase();
}catch(Exception e){
throw new IOException("Caught exception processing input row",e);
}
}
}
and my input file is
100,,King,SKING,515.123.4567,17-JUN-87,AD_PRES,24000,,90
101,Neena,Kochhar,NKOCHHAR,515.123.4568,21-SEP-89,AD_VP,17000,100,90
102,Lex,De Haan,LDEHAAN,515.123.4569,13-JAN-93,AD_VP,17000,100,90
I executed below steps-
1.) emp = LOAD' /home/warehouse/datasets/EMP.csv' USING PigStorage(',') AS (EMPLOYEE_ID:INT,FIRST_NAME:CHARARRAY,LAST_NAME:CHARARRAY,EMAIL:CHARARRAY,PHONE_NUMBER:CHARARRAY,HIRE_DATE:CHARARRAY,JOB_ID:CHARARRAY,SALARY:INT,MANAGER_ID:CHARARRAY,DEPARTMENT_ID:CHARARRAY);
2.) B = FOREACH emp GENERATE EMPLOYEE_ID,myudfs.UPPER(FIRST_NAME) AS LINE;
when i do DUMP B;
I am getting "java.lang.NullPointerException", i think this is because my FIRST-NAME has null have in one of the rows.
i tried removing null values and then dumping the result but still i am getting null pointer exception.
C = FILTER B BY line IS NOT NULL;
DUMP C;
Please help me with this.

or better go with this kind of catch block...so that, only Null Pointer Exception is ignored...
catch(NullPointerException e){
System.out.println("NullPointerException");
return null;
} catch (Exception e){
throw WrappedIOException.wrap("Caught exception processing input row ", e);
}

Change your Catch Block to return null in case of an exception, so job won't stop... somewhat like as shown below...
catch (Exception e) {
System.err.println("Error with ...");
return null;
}

Related

Java NullException

I'm unable to find the solution of this Null Exception.Why this is happening & what is its solution.This is constructor & I'm assigning resultset values to jtable.
public Show_search(ResultSet rst){
ResultSet rs = rst;
int row = 0;
try {
while(rs.next()){
System.out.println("ROW:"+row);
System.out.println(rs.getString("l_name"));
tbl.setValueAt(rs.getString("l_name"), row, 1);//Line 33
row++;
}
} catch (SQLException ex) {
Logger.getLogger(Claim_summary.class.getName()).log(Level.SEVERE, null, ex);
}
}
This is Exception.
Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException
at Gui.Show_search.<init>(Show_search.java:33)
Well the Exception tells you on which line it comes from: 33!
And there you cal tbl.setValueAt, obviously is tbl null!!!
Where does tbl get initialized? is it in the scope of your class (because it is not in the scope of your method)?
you need to initialize it or give it to the method as a parameter!!
It is always good practice to check for null:
if (table != null)
do somthing;
else
do onother thing;

unreported exception IOException; must be caught or declared to be thrown

I have a question , why does java keeps throwing that exception ! Is the problem with the stream ? because I handeled all IOExceptionS !
[[jio0yh.java:12: error: unreported exception IOException; must be
caught or declared to be thrown]]>>
That's the exception that I'm getting!
here is my code
import java.io.*;
public class jio0yh{
public static void main(String[]args){
FileInputStream OD=null;
try{
File f=new File("Binary.dat");
OD= new FileInputStream(f);
byte[]b=new byte[(int)f.length()];
OD.read(b);
for(int i=0;i<b.length;i++)
System.out.println(b[i]);
} catch(FileNotFoundException e){
System.out.println(e.getMessage());
} catch(IOException e){
System.out.println(e.getMessage());
OD.close();
}
}
}
The OD.close(); in your IOException catch block is also susceptible to throwing another IOException.
You should surround the final OD.close() in a finally block:
// ... Any previous try catch code
} finally {
if (OD != null) {
try {
OD.close();
} catch (IOException e) {
// ignore ... any significant errors should already have been
// reported via an IOException from the final flush.
}
}
}
Refer to the following for a more thorough explanation:
Java try/catch/finally best practices while acquiring/closing resources

Exception Handling in java to show user the catch error message from the nested method calls

I have doubt in Exception handling in java,when the exception is thrown in the called method, how to show the catch error in the calling method
Yes, it is possible to catch exception inside called method, and then re-throw same exception back to caller method.
public String readFirstLineFromFile(String path) throws IOException {
try {
BufferedReader br = new BufferedReader( new FileReader (path));
StringBuilder lines = new StringBuilder();
String line;
while((line = br.readLine()) != null) {
System.out.println("REading file..." + line);
lines.append(line);
}
return lines.toString();
} catch(IOException ex) {
System.out.println("Exception in called method.." + ex);
throw ex;
}
}
Note: It is not possible if you are using try with resources, and exception occurred inside resources itself like opening of file, or file not found. In that case exception will be directly thrown back to caller.

ServiceStack catch (WebServiceException ex) - has wrong ErrorCode

In my ServiceStack service, I throw an exception that has an inner exception. When I caught a WebServiceRequest on the client side, the ErrorCode was the inner exception type name.
This is bad for me because it doesn't allow me to respond to the specific exception type that was thrown on the server.
I'm failing to see why ServiceStack was designed this way. It's pretty typical to catch lower level exceptions and wrap them with more informative and sometimes end-user friendly exceptions.
How can I change the default behavior so it uses the surface level exception and not the inner-most?
After looking at the first example at https://github.com/ServiceStack/ServiceStack/wiki/Error-Handling, I decided to check out at DtoUtils.HandleException, which looks like this:
public static object HandleException(IResolver iocResolver, object request, Exception ex)
{
if (ex.InnerException != null && !(ex is IHttpError))
ex = ex.InnerException;
var responseStatus = ex.ToResponseStatus();
if (EndpointHost.DebugMode)
{
// View stack trace in tests and on the client
responseStatus.StackTrace = GetRequestErrorBody(request) + ex;
}
Log.Error("ServiceBase<TRequest>::Service Exception", ex);
if (iocResolver != null)
LogErrorInRedisIfExists(iocResolver.TryResolve<IRedisClientsManager>(), request.GetType().Name, responseStatus);
var errorResponse = CreateErrorResponse(request, ex, responseStatus);
return errorResponse;
}
The very first instruction replaces the exception with it's inner exception. I'm not sure what the the thinking was with that. It seems counter intuitive to me and so I just re-implemented the method in my AppHost class, removing that first if statement block:
public override void Configure(Container container)
{
ServiceExceptionHandler += (request, exception) => HandleException(this, request, exception);
}
/// <remarks>
/// Verbatim implementation of DtoUtils.HandleException, without the innerexception replacement.
/// </remarks>
public static object HandleException(IResolver iocResolver, object request, Exception ex)
{
var responseStatus = ex.ToResponseStatus();
if (EndpointHost.DebugMode)
{
// View stack trace in tests and on the client
responseStatus.StackTrace = DtoUtils.GetRequestErrorBody(request) + ex;
}
var log = LogManager.GetLogger(typeof(DtoUtils));
log.Error("ServiceBase<TRequest>::Service Exception", ex);
if (iocResolver != null)
DtoUtils.LogErrorInRedisIfExists(iocResolver.TryResolve<IRedisClientsManager>(), request.GetType().Name, responseStatus);
var errorResponse = DtoUtils.CreateErrorResponse(request, ex, responseStatus);
return errorResponse;
}
This is obviously not ideal, since I had to copy a bunch of code that is totally unrelated to the problem that I had with the original implementation. It makes me feel like I have to maintain this method whenever I update ServiceStack. I would love to here of a better way to accomplish this.
Anyway, I have the exception handling that I like in my client code:
catch (WebServiceException ex)
{
if (ex.ErrorCode == typeof (SomeKindOfException).Name)
{
// do something useful here
}
else throw;
}
It doesn't seem like you'll have to maintain a bunch of code. You're writing one method to implement your own error handling. You could try calling DtoUtils.HandleException(this, request, exception) in your own method and modify the HttpError object returned. Not sure you have access to change all properties/values you're looking for.
public static object HandleException(IResolver iocResolver, object request, Exception ex)
{
HttpError err = (HttpError)DtoUtils.HandleException(this, request, ex);
err.Reponse = ex.InnerException;
}

Exception handling and constructors

I am writing data to a file, when I write this data I want to do it so that if the file does not open it will give the user a message saying that something whent wrong. The way I do this is by calling the method to write, if it fails it returns false. That way I can prompt the user to do something to check what has happened.
However when I create the object I cant return anything from the constructor so I am a bit stumped about what I should do.
public class Writetofile {
BufferedWriter writer = null;
public Writetofile(String[]details) throws IOException{
String machine= details[0];
String date=details[1];
String start_time = details[2];
try{
File new_cal= new File("C:\\Activity_Calibrator\\log\\"+machine+"\\"+machine+date+".txt");
new_cal.getParentFile().mkdir();
FileWriter fwriter = new FileWriter(new_cal);
writer = new BufferedWriter(fwriter);
writer.write("Linear Calibratiton for " + machine + " carried out " + date+" ./n");
writer.close();
}
catch(Exception e){ in here I would like to be able to send a message back to m
code so that it can tell the user to check the folder etc}
}
when I call the record data if something goes wrong it will return a false to the calling class. and I can put a message.
public boolean recordData(String record) throws IOException{
try{
writer.append(record);
writer.close();
return true;
}
catch(Exception e){
return false;
}
}
}
}
A constructor should not DO anything. A constructor is an initialization phase closely tied to the allocation of an object.
Throwing exceptions, or doing anything in a constructor that might throw an exception is to be avoided.
Java does not separate the phases of allocation and initialization, no code, especially IO code should be in a constructor.